Can't fetch a single item from an API with React Native

I'm consuming an API with React Native and I'm trying to set one item to display it's attributes but I can't get the object from the API.

This is the code I'm using, which was working perfectly when I was working with arrays of objects from the same API.

const url = `https://2bgo6ptw6j.execute-api.us-east-1.amazonaws.com/dev/client/99a00a42-cbc8-43e7-9b43-14b98684540f`
    const [client, setClient] = useState();
    useEffect(() => {
      console.log('asd');
      fetch(url)
          .then((response) => response.json())
          .then((json) => {
          console.log(json);
          setClient(json);
          })
          .catch((e) => {
          console.log(e);
          })
  }, []);
    const male = "Masculino";
    const female = "Femenino";
    let message;

    if (client.gender === 'M') {
      message = male;
    } else {
      message = female;
    }

And this is the object that is returned from that URL:

{
"clientName":"Diego",
"lastName":"Penaranda",
"SK":"#METADATA#99a00a42-cbc8-43e7-9b43-14b98684540f",
"PK":"CLIENT#99a00a42-cbc8-43e7-9b43-14b98684540f",
"phone":76948002,
"clientId":"99a00a42-cbc8-43e7-9b43-14b98684540f",
"gender":"M",
"type":"client"
}

I don't even recieve the console logs inside the useEffect, I directly get this message: "Cannot read property 'gender' of undefined."

Upvotes: 0

Views: 379

Answers (1)

Tur1ng
Tur1ng

Reputation: 834

You are trying to reference client.gender before the client is even set: On first render, client will be undefined while the fetch is happening. Only after the fetch completes will the client be set to an object. So you need to check if client !== undefined before trying to access any properties you think the result should have.

A tip: Get good at reading and understanding common error messages like this. "Cannot read property 'gender' of undefined." is a helpful error message because it's exactly what's happening, so if you understood the error message, I'm sure you wouldn't have needed to post this question :).

Upvotes: 2

Related Questions