Accepted answer

First of all, if you pass an empty array for initial data to useState, you can't get any item in that array in here:


Because component returns first item of an array that has nothing. I prefer to you do it like this:

  <h1>{carouselTitle.length > 0 && carouselTitle[0].id}</h1>

And also based on this and official documentation, setState (and also setSomthing() using useState()) is asynchronous.

So state data doesn't show immediately after setting that.


You should trigger useEffect for run fetch function



setState is asynchronous :

It means that you cannot expect to console.log the new state value the line after you called setCarouselTitle.

To log the new value, you could use another useEffect, with carouselTitle in the dependencies array, where you console.log(carouselTitle) :

useEffect(() => {
}, [carouselTitle]);

That said, your component should behave correctly, it will be refreshed when the state is updated.

In the JSX you should check that carouselTitle is not undefined (meaning that the request failed or is still pending) :

{carouselTitle && <H1>{carouselTitle[0].id}}

Related Query

More Query from same tag