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.