0

I have the following code:

const [intrebari, setIntrebari] = useState([])
     useEffect(() => {
          let idVar = localStorage.getItem('idVarianta');
          idVar = JSON.parse(idVar)
           axios({
             method: "POST",
             data: {
               idVarianta: idVar,
             },
             withCredentials: true,
             url: "http://localhost:4000/getIntrebari",
           }).then((res) => {
              console.log(res)
              const data = res.data;
           setIntrebari(data);
            console.log('Data has been recieved');
           });
        }, [])

which is returning me this: enter image description here

How can I access the data? If I try intrebari[0].intrebare it gives me "Cannot access property intrebare of type undefined". Any idea? I tried also to console log intrebari[0] and it's displaying the first element, but when i'm trying to access intrebari[0].intrebare it gives me the error described above. Thanks

2 Answers 2

1

Instead of setIntrebari(data), try setIntrebari(res).

Sign up to request clarification or add additional context in comments.

1 Comment

Try putting the axios call in an async function (await the axios call), and await the results in the effect hook.
0

Solved it by adding this. The problem was that the component was rendering before the data was fetching.

function getIntrebare() {
      if (intrebari.length !== 0) {
        return intrebari[questionIndex].intrebare;
      }
      return "";
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.