Uncaught (in promise) TypeError: Cannot use ‘in’ operator to search for ‘path’ in undefined

I am a new learner. I am trying to add cart feature using vue. Here is my view name Cart.vue for the cart.

<template>
    <div class="page-cart">
        <div class="columns is-multiline">
            <div class="column is-12">
                <h1 class="title">Cart</h1>
            </div>

            <div class="column is-12 box">
                <table class="table is-fullwidth" v-if="cartTotalLength">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Price</th>
                            <th>Quantity</th>
                            <th>Total</th>
                            <th></th>
                        </tr>
                    </thead>

                    <tbody>
                        <CartItem
                            v-for="item in cart.items"
                            v-bind:key="item.product.id"
                            v-bind:initialItem="item" />
                    </tbody>
                </table>

                <p v-else>You don't have any products in your cart...</p>
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios'
import CartItem from '@/components/CartItem.vue'
export default {
    name: 'Cart',
    components: {
        CartItem
    },
    data() {
        return {
            cart: {
                items: []
            }
        }
    },
    mounted() {
        this.cart = this.$store.state.cart
    },
    computed: {
        cartTotalLength() {
            return this.cart.items.reduce((acc, curVal) => {
                return acc += curVal.quantity
            }, 0)
        },
    }
}
</script>

This is the CartItem.vue component that I used:

<template>
    <tr>
        <td><router-link :to="item.product.get_absolute_url">{{ item.product.name }}</router-link></td>
        <td>Rs {{ item.product.price }}</td>
        <td>
            {{ item.quantity }}
        </td>
        <td>Rs {{ getItemTotal(item).toFixed(2) }}</td>
        <td><button class="delete"></button></td>
    </tr>
</template>

<script>
export default {
    name: 'CartItem',
    props: {
        initialItem: Object
    },
    data() {
        return {
            item: this.initialItem
        }
    },
    methods: {
        getItemTotal(item) {
            return item.quantity * item.product.price
        }
    },
}
</script>

I cannot see any product and the related values in the cart. I am getting this error –
Uncaught (in promise) TypeError: Cannot use ‘in’ operator to search for ‘path’ in undefined.
I am unable to find out the mistake in my code. Please help me out. When I am removing the component from the cart.vue, then the error gets eliminated. But I need that component.

Arrays not getting sorted after async function

On a screen on my app I have a useEffect hook that retrieves some info about a user for a notification, after that I want to get all the notifications array sorted by date, the problem is that the arrays doesn’t seem to get sorted:

useEffect(() => {
  const arrayNotifications = [];
  const arrayRequests = [];

  notificationsAndRequests.forEach(async notif => {
    const senderSnapshot = await database().ref(`/users/${notif.sender}`).once('value');
    let senderImage = (senderSnapshot.val() && senderSnapshot.val().userImg);

    if (notif.sender == null) {
      const recieverSnapshot = await database().ref(`/users/${notif.sender}`).once('value');
      senderImage = (recieverSnapshot.val() && recieverSnapshot.val().userImg);
    }

    const element = {
      date: notif.date,
      id: notif.id,
      isInvitation: notif.isInvitation,
      message: notif.message,
      reciever: notif.reciever,
      sender: notif.sender,
      senderimage: senderImage,
      timestamp: notif.timestamp,
      title: notif.title,
      extraid: notif.extraid,
      requestid: notif.requestid,
      viewed: notif.viewed,
      status: notif.status || ''
    };

    if (notif.isInvitation) {
      arrayRequests.push(element);
    } else {
      arrayNotifications.push(element);
    }
  });
  const sortedNotifications = arrayNotifications.sort(
    (a, b) => Date.parse(mom(b.timestamp, 'YYYY-MM-DD HH:mm').toDate())
    - Date.parse(mom(a.timestamp, 'YYYY-MM-DD HH:mm').toDate())
  );
  const sortedRequests = arrayRequests.sort(
    (a, b) => Date.parse(mom(b.timestamp, 'YYYY-MM-DD HH:mm').toDate())
    - Date.parse(mom(a.timestamp, 'YYYY-MM-DD HH:mm').toDate())
  );

  setNotifications(sortedNotifications);
  setRequestsNotifications(sortedRequests);
}, [notificationsAndRequests]);

Both sortedRequests and sortedNotifications should be ordered by the timestamp property of the notif object (timestamp is just a string formatted as a date).
Should I sort both arrayRequests and arrayNotifications instead?

Question about how to treat the “this” keyword in TypeScript. (Vue project)

I’m fairly new to TypeScript and I’m running into an issue. I have a .ts I’m using to store some helper functions. These functions are called via .call so the proper this is referenced. In that file, each this gives the following two errors:

'this' implicitly has type 'any' because it does not have a type annotation.

An outer value of 'this' is shadowed by this container.

An example of one of the helpers:

export function setEditId(id: string) {
  this.editTodoId = id;
}

Here’s the repo (it’s small): https://github.com/colebillys19/vue-todo-typescript The file in question is App.helpers.ts.

For additional context, I got the project up and running without TypeScript and everything works fine. That repo is here if you’re interested: https://github.com/colebillys19/vue-todo

How to use an API response as initial value for input in ReactJS

Hello I am trying to make an input field that already has a preset value from an API response in ReactJS. I’ve tried using console.log(data[0].name) and it showed the value I was expecting and when I tried to show it in the frontend it also works fine. But when I try to show it as an initial value for my input field, it just gives me an empty input field. initialValue = {data[0].name}

Here’s my app.js

import React, { useEffect, useState } from "react";
import { Form, Button, Input } from "antd";

function App() {
  const [data, setData] = useState([{}]);
  const [form] = Form.useForm();
  const onFinish = (values) => {
    console.log("Received values of form: ", values);
  };

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/1/comments")
      .then((res) => res.json())
      .then((data) => {
        setData(data);
        console.log(data);
      });
  }, []);

  return (
    <div>
      {" "}
      <Form form={form} onFinish={onFinish}>
        <Form.Item
          className="Form-label"
          name="firstName"
          label="First Name"
          initialValue={data[0].name}
        >
          <Input
            maxLength={10}
            style={{ minWidth: 200, maxWidth: 500 }}
            placeholder="Enter First Name"
          />
        </Form.Item>
        <Form.Item
          className="Form-label"
          name="middleName"
          label="Middle Name"
          initialValue=""
        >
          <Input
            maxLength={10}
            style={{ minWidth: 200, maxWidth: 500 }}
            placeholder="Enter Middle Name"
          />
        </Form.Item>
        <Form.Item>
          <div className="Btn-Primary-Create-Employee">
            <Button type="primary" htmlType="submit">
              Save
            </Button>
          </div>
        </Form.Item>
      </Form>
    </div>
  );
}

export default App;

Here’s the object im fetching

[
  {
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "[email protected]",
    "body": "laudantium enim quasi est quidem magnam voluptate ipsam eosntempora quo necessitatibusndolor quam autem quasinreiciendis et nam sapiente accusantium"
  },
  {
    "postId": 1,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "[email protected]",
    "body": "est natus enim nihil est dolore omnis voluptatem numquamnet omnis occaecati quod ullam atnvoluptatem error expedita pariaturnnihil sint nostrum voluptatem reiciendis et"
  }
]

I’ve also made a codesandbox project to better visualize my issue

Unable to check if a button is disabled in javascript [duplicate]

I am trying to check if a button is disabled in testcafe. Below is my code:

test('Verify  button is inactive after disabling button functionality', async (browser) => {
  await browser.wait(5000);
  const button = '[data-testid=Button]';
  await browser.click(button);
  const buttonActive = ClientFunction(() => {
    const button = '[data-testid=Button]';
    const buttonStatus = button.disabled;
    console.log(buttonStatus);
    return buttonStatus;
  });

  await browser.expect(buttonActive()).eql(false);
});

this reports an error – TypeError: Cannot read properties of null (reading ‘disabled’)

I tried querying from browser console and it worked –

document.querySelector('[data-testid=Button]').disabled
false

Any idea why it is not working?

Making curl requests to ganache server hosted locally

I’m trying to figure out how to make requests to a local ganache server. This is my first time using Ganache so forgive me if this should be obvious.

My end goal is to have a dedicated server hosting ganache, that I will be able to make curl requests to at any time. The hosted ganache server will be designed to fork mainnet every so often and respond to requests.

I’ve tried ganache-cli --fork which yields this in the terminal:

ganache v7.0.3 (@ganache/cli: 0.1.4, @ganache/core: 0.1.4)
Starting RPC server

Available Accounts
==================
(0) 0xbDF9C183567A386609e6e94d0aD13CeA8f374049 (1000 ETH)
(1) 0xe27b1B229b768Adca934CEd15faA0b3C5Cf48781 (1000 ETH)
(2) 0x637F0C83B8B682282E291Ce0DDb1E90b1cA7b106 (1000 ETH)
(3) 0xDa94450449dE31AF4ca977656d267991912f4e32 (1000 ETH)
(4) 0x9ef0A0392D8273221786A97a9E5C4c4Db0C1a713 (1000 ETH)
(5) 0x31b442a7e5799DE23F8925E5a40BCb6dea5B3092 (1000 ETH)
(6) 0xA011e621A9E298333266E190A7F2A85d7D24Bd84 (1000 ETH)
(7) 0x349A93BAC6e637e5b9405E7ea67d43E806bEF636 (1000 ETH)
(8) 0x55038A17ad748749E39BAb2aB22F957243cf3eC2 (1000 ETH)
(9) 0x2AfebF0d8020dCe1AA50FEf6B97624E1Bde5CBB7 (1000 ETH)

Private Keys
==================
(0) 0x0e79efa9a1a642978b194d8d2a81169dfd270ac91cc2263366bf36bc2fa364c6
(1) 0x5114080f5d56b72e56fa12bf058e921418425f17e2054a45a094ec7765da5336
(2) 0xbf2552187bed065e05528cc21790ab6df0eecbbb879374fb64ee6c9f0198cb8a
(3) 0x6198d636b7a7c292ff6f3c782a0e19e81ab51c3ef13453ac52afcb957284d24f
(4) 0x59a322108f123ac90beabd8842622d60bb42e2e53d31f1b93f8f4938933149c9
(5) 0xcca307c9935aa2587f7e356cd6de410d2133c45ecc783ca24d8598fafc2c1ad9
(6) 0x14304aa76ecb5626e6d2fa4292580d2f84e8fe0efee8c66903043a490ed41021
(7) 0xc382db92c9eaf40cc104f08292e47c290213044bb7998cd135f22788da8b99ff
(8) 0x7495fd3615831af0e0de59beaa56d813e71cf25db0f11069b195ca39fb9701b6
(9) 0x0351c7990ff699ad7a4d669667f426f96e0590f2c6ebd2b1241edb6317bba3a3

HD Wallet
==================
Mnemonic:      wrap tired exhaust oil seed teach comfort flash wasp error else still
Base HD Path:  m/44'/60'/0'/0/{account_index}        

Default Gas Price
==================
2000000000

BlockGas Limit
==================
30000000

Call Gas Limit
==================
50000000

Forked Chain
==================
Location:        Ethereum Mainnet, via 丕Infura      
Block:           14523327
Network ID:      1
Time:            Mon Apr 04 2022 22:46:30 GMT-0400 (Eastern Daylight Time)

Chain Id
==================
1337

RPC Listening on 127.0.0.1:8545

While this is still running, in a separate terminal, I’m running curl.exe http://127.0.0.1:8545 -X POST -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method": "eth_accounts"}' just to test that I can get some kind of response (Note: using curl.exe because I had problems with curl in powershell). I always get this error 400 Bad Request: Unexpected token j in JSON at position 1

Is this an issue with ganache-cli being an rpc server rather than json-rpc? How can I start a server that is json-rpc in that case?

I’ve also tried making a server programmatically by following along with Ganache documentation that specifies that the code is designed to be a json-rpc server:

const ganache = require("ganache");

const options = {};
const server = ganache.server(options);
const PORT = 8545;
server.listen(PORT, async (err) => {
  if (err) throw err;

  console.log(`ganache listening on port ${PORT}...`);
  const provider = server.provider;
  const accounts = await provider.request({
    method: "eth_accounts",
    params: [],
  });
});

I get the same error when trying to make a curl request. Can someone help me figure out what I’m doing wrong?

Thanks!

React useState not showing changes [duplicate]

I have a very large component, so I’ll try to show a portion of the code below that is important. But, essentially, when I attempt to remove a filter via a custom function that calls useState() I can see, via the console, that the state does indeed change, but the changes don’t present themselves.

const DraftClassExplorerHeader: React.FC<{ selectedFilters: any[] }> = (
  props
) => {
  let [selectedFilters, setSelectedFilters] = React.useState<any[]>(
    props.selectedFilters
  );
  let globalState = React.useContext(DraftClassExplorerContext);
  React.useEffect(() => {
    setSelectedFilters(props.selectedFilters);
  }, [props.selectedFilters]);

  const removeFilter = (c: number) => {
    let temp = selectedFilters;
    temp.splice(c, 1);
    globalState.setSelectedFilters(temp);
  };
....

I’ve tried using useEffect() within the removeFilter function, but React is not a fan of that it seems. Any help greatly appreciated.

Edit: my question is definitely different from the proposed duplicate because I am asking explicitly about using React hooks here.

Get the open graph image for a webpage? (The way facebook embeds a thumbnail image when you share its link)

On my webpage I want to share a link – let’s say to this wikipedia page for Superhero

In the code for that page there is the following code in the head tag:

<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Connecticut_ComiCONN_Superhero_Mascot..jpg/640px-Connecticut_ComiCONN_Superhero_Mascot..jpg">

This is the thumbnail for that page that is shown if you share the link on social media. (Most pages now have one).

Is there a way to retrieve that image url to embed on my normal webpage page?

I’m using CSS, HTML and Javascript.

mapping of an empty array, error checking logic

I am new to react and a question on how to handle empty arrays. I have some data on a specific class. The class data can be seen below. I am trying to display the data in my web app but I have having trouble with the logic of mapping array when they are empty.

a simplified version of my code is shown below:

import React from 'react';
import { useState, useEffect } from "react";

const data = {
  ece1004: {
    number: "ECE 1004",
    name: "Introduction to ECE Concepts",
    des: "Introduction to topics that span the field of electrical and computer engineering (ECE). Content presented through the lens of application with accompanying hands-on exercises. Basics of circuits, op-amps, power supplies, computer logic, system decomposition, and coding. Modeling and application of engineering professionalism. Exploration of ECE in society.",
    pre: [["ENGE 1215", "ECE 1414"]],
    co: [],
    minGrade: "C",
    offering: ["Fall", "Spring", "Summer"],
  }
};

function ECE1004() { 
    const [data, setData]  = useState([]);

    const fetchClassObj = () => {
        setData(data);
    }
    useEffect(() => {
        fetchClassObj();
    },[]);

    return (
        <>   
            <div>
                {data.co ? 
                    data.co.map(coreq => {
                    return(      
                    <div className="classDes">
                        Coreqs: {coreq.join(', ')}
                    </div>
                    )
                }) : <h3>No data yet</h3> }
                
            </div>             
        </>
    )

}

export default ECE1004

I would like the class data to be displayed all in separate divs. For example, if I wrote the same code for the prereqs, it would display as “Prereqs: ECE 1215, ECE 1414” with a comma inbetween (hence the .join(', ') function).
However, since the co member of the data is empty the mapping function is not recognized. I was wondering what the logic is to check if the array is empty as well as use the .join(', ') function.
I have tried not mapping the data and using {data.co.length ? 'coreqs' + data.co.join(', ') : 'coreqs: None'} but then the .join(', ') is not recognized.
Any help would be appreciated, thank you.

Component returning nested React Elements not displaying

I have a default component Collection which uses a sub-component called RenderCollectionPieces to display UI elements. I can’t figure out why I am able to see the data for image.name in the console but not able to see the UI elements display.

Additional information:

  • There are no errors in the console
  • If I replace <p>{image.name}</p> with <p>TESTING</p>, still nothing shows.
  • columnOrg is a list of lists
  • each list in columnOrg is a list of maps with some attributes

Index.js:

const RenderCollectionPieces = () => {
  const {collectionId} = useParams();  
  let listOfImageObjects = collectionMap[collectionId];
  let imagesPerColumn = Math.ceil(listOfImageObjects.length / 4);
  let columnOrg = [];

  while (columnOrg.length < 4){
    if(imagesPerColumn > listOfImageObjects.length){
      imagesPerColumn = listOfImageObjects.length;
    }
    columnOrg.push(listOfImageObjects.splice(0,imagesPerColumn))
  }
 
  let collectionList = columnOrg.map((col) => {
        return(            
            <Grid item sm={3}>
              {
                col.map((image) => {
                  console.log(image.name)
                  return(
                    <p>{image.name}</p>
                  )
                })
              }
            </Grid>
        )
    });
  return collectionList;
};

const Collection = ({ match }) => {
  const {collectionId} = useParams();
  return(
    <Box sx={{ background:'white'}}>
      <Grid container>           
        <RenderCollectionPieces />          
      </Grid>
  </Box>
  )
};

export default Collection;

reactjs – owl carousel links inside body arent clicking

I’ve created an owl carousel and I wanted to add some external links to my repositories that the user can click.

I cannot seem to click the links inside the body. I have played around with the z-index but still no luck. can anyone take a look at my code and css and let me know if I am missing anything obvious?

  return (
    <div className="projects-container">
      <ScreenHeading
        title={"Projects"}
        subHeading={"My Projects I have Worked On"}
      />
      <section className="projects-section" id={props.id || ""}>
        <div className="container mt-5">
          <OwlCarousel
            className="owl-carousel"
            id="projects-carousel"
            {...options}
          >
            <div className="ms-2 me-2">
              <div className="card">
                <img
                  src="img/projects/tweets.jpg"
                  className="card-img-top"
                ></img>
                <div className="card-body">
                  <h5 className="card-title">
                    {" "}
                    COVID-19 Twitter Misinformation NLP Machine Learning
                    Research Project
                  </h5>
                  <p>
                    Developed multiple ML algorithms to classify 31,000 tweets
                    related to COVID-19 as factual/false. Tweets scraped using
                    Twitter API.
                  </p>
                  {/* <div class="box-btn">
                    <span>
                      <a href="#">Repo Link</a>
                    </span>
                  </div> */}
                </div>
              </div>
            </div>
            <div className="ms-2 me-2">
              <div className="card">
                <img
                  src="img/projects/vet-app.jpg"
                  className="card-img-top"
                ></img>
                <div className="card-body">
                  <h5 className="card-title"> Veterinary App</h5>
                  <p>
                    Full stack Application developed for the Veterinary School
                    of Medicine to help manage and care for animals. Multiple
                    user roles utilizing Restful API This project involved
                    database design, API creation and authentication.
                  </p>
                  <div className="box-btn">
                    <span>
                      <a href="">Repo Link</a>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div className="ms-2 me-2">
              <div className="card">
                <img
                  src="img/projects/movie-ticket.jpg"
                  className="card-img-top"
                ></img>
                <div className="card-body">
                  <h5 className="card-title">
                    {" "}
                    Movie-Theatre-Ticket-Reserveration-App
                  </h5>
                  <p>
                    Full stack Java application using utlizing MVC design
                    pattern that simulates reserving seats and movie tickets at
                    a theatre. The design of this project focused on JDBC, and
                    Swing
                  </p>
                  <div className="box-btn">
                    <span>
                      <a href="">Repo Link</a>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div className="ms-2 me-2">
              <div className="card">
                <img
                  src="img/projects/capstone.jpg"
                  className="card-img-top"
                ></img>
                <div className="card-body">
                  <h5 className="card-title"> Capstone Project</h5>
                  <p>
                    Developed a proof-of-concept machine learning application
                    used to predict an aircraft engine's ​performance.​
                    Developed front-end client application to make inferences
                    through deployed model.
                  </p>
                  {/* <div class="box-btn">
                    <span>
                      <a href="#">Repo Link</a>
                    </span>
                  </div> */}
                </div>
              </div>
            </div>
            <div className="ms-2 me-2">
              <div className="card">
                <img
                  src="img/projects/pippa.jpg"
                  className="card-img-top"
                ></img>
                <div className="card-body">
                  <h5 className="card-title">
                    {" "}
                    Hackathon - 2022 (PIPPA)
                  </h5>
                  <p>
                    Application developed for 2022 Hackathon. Developed to
                    educate and provide insight to common pressure point related
                    injuries for bed-restricted patients. Functional log-in
                    feature.
                  </p>
                  <div class="box-btn">
                    <span>
                      <a href="">Repo Link</a>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div className="ms-2 me-2">
              <div className="card">
                <img
                  src="img/projects/portfolio-website.jpg"
                  className="card-img-top"
                ></img>
                <div className="card-body">
                  <h5 className="card-title"> Personal Website</h5>
                  <p>
                    My personal website designed to showcase my work and
                    experience. Created utilizing ReactJS, Boostrap, Rxjs, and
                    NodeJS.
                    <br></br>
                    <br></br>
                    <br></br>
                  </p>
                  <div className="box-btn">
                    <span>
                      <a href="">Repo Link</a>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </OwlCarousel>
        </div>
      </section>
  

<div className="footer-image">
    <img src={shape} alt="check your internet!" />
  </div>
</div>
  );
}

css file

.projects-section {
  padding: 80px 0 55px;
  background-image: url("../../../src/assets/Projects/bg-1.jpg");
  background-position: center;
  background-attachment: fixed;
  position: relative;
  z-index: -1;
}

.owl-dots {
  text-align: center
}

.

card-img-top{
  height: 20vh;
  width: 100%;
}
.card-body{
  z-index: 500;
  height: 250px;
  width:100%;
  object-fit: cover;
}

.card-title{
  font-weight: bold;
}

.box-btn {
z-index: 1000;
display: block;
width: 100%;
height: 100%;
position: relative;
}

.owl-item > div {
  pointer-events: auto !important;
}

.footer-image {
  width: 100%;
  height: 100%;
  max-width: 1920px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  margin-top: -110px;
  z-index:-1;
}
.footer-image img {
  max-width: 100%;
  height: 130px;
  z-index: -1
}

Properly handling exceptions from async functions at the top level

I’m having trouble understanding the correct way to handle exceptions from async functions without triggering Node’s UnhandledPromiseRejectionWarning (since that seems to suggest that I’m doing something wrong).

Normally, in non-async code, unhandled exceptions bubble all the way to the top and eventually get printed to the console. The code that resulted in the exception is stopped all the way back up the stack.

Say I have the following code:

test1().catch((e) => { throw e; });
console.log('got here top-level'); // This will print

async function test1() {
    let test2Result = await test2();
    console.log('got here test 1'); // This won't print
    return test2Result;
}

async function test2() {
    throw new Error('something failed here');
}

I would expect that this would do what I want. At the top-most level, it catches the exception from the async functions and re-throws (but now outside any async code or Promises). It should still have the original stack trace so I can find the problem. Happy days, right? But no, this still results in UnhandledPromiseRejectionWarning and I don’t understand why.

What’s the proper way to catch all unhandled exceptions from inside Promises?

Access Div Based on Another in JQUERY

How do I access the <a ....>General</a> base on this div I’m getting below on “test”?

test

<div
    role="tabpanel"
    class="panel-collapse collapse" 
    id="collapseGeneral"
    aria-labelledby="collapseGeneral"
    style="height: auto"
  >
    <div class="panel-body">
      ...
    </div>
  </div>

GIVEN

<div class="panel panel-default">
  <div role="tab" class="acc-heading" id="headingGeneral">
    <a
      data-toggle="collapse"
      role="button"
      aria-expanded="false"
      data-parent="#accordion"
      class=""                        
      href="#collapseGeneral"
      aria-controls="collapseGeneral"
      >General</a
    >
  </div>
  <div
    role="tabpanel"
    class="panel-collapse collapse" 
    id="collapseGeneral"
    aria-labelledby="collapseGeneral"
    style="height: auto"
  >
    <div class="panel-body">
      ...
    </div>
  </div>
</div>

code

  console.log(jQuery(test).parent(), "parent");

What is the best practice in this situation Async Await with try/catch or Promise.then().catch()?

I try to create a function that returns values ​​from the server, if one of the values ​​returns with an error then everything that comes back to me from the function falls and I get NULL,
If I use try / catch the problem is solved.
What is the best solution in terms of performance and something that can work in the result I want

public async getUserById(id: number): Promise<dto> {
  const arr = [];
  const user = await this.userService.getUserById(id);
  try {
  const company = await this.companyService.getCompanyIdToken(
    user.company_id
  );

  UsersProvider.setUserCompany(user, company);

  for (const space of user.spaces) {
    try {
      const Response = await this.companyService.getSpaceById(space);
      arr.push(Response);
    } catch (error) {
       console.log(error) **// Here I expect you not to throw an error**
    }
  }
} catch (error) {
  console.log(error) **// Here I expect you not to throw an error**
}
return user;

}

LocalStorage.getItem not working properly

Basically I am using Pycharm for the first time to create a web application connected to Python. I am trying to send data between two HTML files. I noticed it was not working so I tried on a single file. When I click run main, it works and prints

i|f;/ITV?vqy<{/giT(7/0cFk%JC&iiW8ZL,RY<HwTN~mRd,V(iL+jqeJKdk>fJO~Y<a+0w7L3t!vagdV"pqDVy5_yK[}=a8Sj^,Xq#MmLX7g2<^cE`BBQ+*v?#2O`tvWT<mL"~$PePa:_`Y<PP:hf|wR~W&P[YB6nKmpql"n?]]HY`qq3@*b~q#27P!0>E]^N81H.$;=I-a;:dqAq)u!FDMhn)qs_I,bjhdJA1q8i[Z$CO?o:Kdu!7eU%v`z.0e

but if I just open the HTML page, it’s undefined. I feel like the other issue is similar. The only difference I know is the URL. When I do run main, the URL is

http://127.0.0.1:5000/

otherwise, it is

http://localhost:63342/main.py/templates/main.html?_ijt=gg9rhi2jh5afgf7fngill850rc&_ij_reload=RELOAD_ON_SAVE

Does anybody know how to fix this or another method? I’ve read that if you add the script file, then you can access the variable. Is that true? Another issue with that is that PyCharm CE does not allow separate JS or CSS files, so I’d need a new IDE