0

I am trying to set the state of my variable with data fetched using the useEffect hook but when I call the setState() function and pass it the fetched data, the state remains null. The fetch statement works as I can log the data to the console but for some reason the setState doesn't take the data. Can anyone please tell me where I am going wrong?

Here is the useState and the useEffect:

 const [products, setProducts] = useState(null);

 useEffect(() => {
        fetch('http://127.0.0.1:8000/api_products/')
        .then(res => {
            return res.json();
        })
        .then((data) => {
            console.log(data);
            setProducts(data);
            console.log(products);
        })
    }, [])

And here is the data that gets logged to the console. It's an array of Javascript objects:

[
{id: 1, name: 'Cookies', shipping: 'Nationwide', image: '/images/NYC_Cookie_Choc_Chip.jpg'},
{id: 3, name: 'Banana Bread', shipping: 'Glasgow Only', image: '/images/Banana_Bread_Slice.jpg'},
{id: 4, name: 'Cupcakes', shipping: 'Glasgow Only', image: '/images/Cupcake_Double_Choc.jpg'},
{id: 2, name: 'Brownies', shipping: 'Nationwide', image: '/images/Brownies_MAcbMQf.jpg'}
]

Am I trying to set the state to be the data fetched so I can map through the array and display the data on the web page. The console.log(products) line keeps returning null. Any advice or ideas would be massively appreciated! Been scratching my head on this one for a while.

1 Answers1

1

State updates are async, therefore you cannot console the output immediately. Rest assured, your data is likely being set.

The best way I've found to console the output is through useEffect:

useEffect(() => {
    console.log(products)
    //Or, take some action
  }, [products])

Similarly, you'll need to useEffect if you want to act upon a state change immediately once it's complete. I've shown this in my comment above for Or, take some action.

Jlove
  • 239
  • 1
  • 7
  • Thanks this helped me figure it out! I was wondering why when I tried to map out the state when the page rendered it returned an error saying it can't read property of null.map. Your answer helped me realise that there is a time lag between the page loading and the data fetching. You were right the state was being set but after the page was loading hence the map function wasn't working. I fixed it by adding a conditional {products && products.map ...} and that fixed the issue. Thanks again! – Michael Hird Jul 06 '22 at 11:26
  • Sounds great, glad you figured it out @MichaelHird – Jlove Jul 06 '22 at 13:12