I am new to React and having trouble with useState/useEffect :
function WinesInMyCave() {
const [winesList, setWinesList] = useState({});
const [isDataLoading, setDataLoading] = useState(false);
useEffect(() => {
console.log("Got this far 1");
async function fetchWine() {
console.log("Got this far 2");
setDataLoading(true);
const response = await fetch("http://localhost:3000/api/wines", {
method: "GET",
})
const { winesList } = await response.json()
setWinesList(winesList)
setDataLoading(false)
}
fetchWine()
}, []);
console.log(winesList);
console.log(isDataLoading);
return (
...
)
With the console.logs I added, I see that the useEffect is never called, thus the function fetchWine is not called either.
And if I set
const [isDataLoading, setDataLoading] = useState(**true**);
I see that the useEffect is called ("Got this far" 1 & 2 showing)
Can somebody help me please ?
Thanks in advance
2
Answers
Here is the solution :
I had set winesList has an object, but the API send an array, furthermore it needed to delete the {} for
const { winesList } = await response.json()
as it was not needed to deconstruct the constant.Thanks for you help !
Try to leave only the function call in the useEffect.
Place the function itself outside
Also, set loading to false only once you have your data.
The code should look something like this :