anto6314
anto6314

Reputation: 47

React: TypeError Cannot read properties of undefined (reading '0')

I am working on a React App, and i'm trying to get some data using an axios GET request from my node backend.

the Api Endpoint i'm currently using that regard this problem is the following:

// NodeJS Backend
app.get('/v1/companys/user/:user_uuid', verify, (req, res) => { // GET - Company by User UUID
    const selectQuery = 'SELECT * FROM companys WHERE uuid = (SELECT company_uuid FROM users WHERE uuid = ?)';
    connection.query(selectQuery, [req.params.user_uuid], (err, results) => {
        if(err) {
            res.send(err)
        } else if (results.length === 0) {
            res.json({status: 404, message: 'Company not found'})
        } else {
            res.json({data: results})
        }
    });
});

This is my Front End:

// ReactJS FrontEnd
const companyLogo = userCompany ? userCompany.logo_url : null;

  console.log(userCompany);

  useEffect(() => {
    const getUserCompany = async () => {
      try {
        await axios.get(process.env.REACT_APP_API_URL + 'companys/user/' + userUuid).then((response) => {
          console.log("response "+ response);
          let res = response.data.data[0];
          console.log(res);
          setUserCompany(res);
        });
      } catch (error) {
        console.log(error);
      }
    };
    getUserCompany();
  }, [userUuid]);

There app works fine, but on the console the following error appear:

The object below the error is in fact the thing that i need (companyLogo)

I was wondering if someone know what am I doing wrong on my frontend to fix the TypeError.

Thanks for the help!

enter image description here

Upvotes: 0

Views: 1746

Answers (1)

Tim van Dam
Tim van Dam

Reputation: 465

If you use optional chaining (?.) to catch possible null/undefined values, you'll most likely fix the issue.

So like this: let res = response.data.data?.[0];

Upvotes: 3

Related Questions