score:1

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:

return(
  <h1>{carouselTitle[1].id}</h1>
)

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

return(
  <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.

score:-1

You should trigger useEffect for run fetch function

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

score:5

setState is asynchronous : https://reactjs.org/docs/faq-state.html#why-doesnt-react-update-thisstate-synchronously

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(() => {
  console.log(carouselTitle);
}, [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}}

https://reactjs.org/docs/conditional-rendering.html#gatsby-focus-wrapper


Related Query

More Query from same tag