skip to Main Content

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


  1. Chosen as BEST ANSWER

    Here is the solution :

    function WinesInMyCave() {
    const [winesList, setWinesList] = useState([]);
    const [isDataLoading, setDataLoading] = useState(false);
    
    useEffect(() => {
    async function fetchWine() {
      setDataLoading(true);
      const response = await fetch("http://localhost:3000/api/wines", {
        method: "GET",
      });
      const winesList = await response.json();
      setWinesList(winesList);
      setDataLoading(false);
    }
    fetchWine();
    }, []);
    
    return (
    ...
    )
    

    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 !


  2. 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 :

    function WinesInMyCave() {
      const [winesList, setWinesList] = useState({});
      const [isDataLoading, setDataLoading] = useState(true);
    
      async function fetchWine() {
        const response = await fetch("http://localhost:3000/api/wines", {
          method: "GET",
        })
        const { winesList } = await response.json()
        setWinesList(winesList)
        setDataLoading(false)
        console.log(winesList);
        console.log(isDataLoading);
      }
    
      useEffect(() => {
        fetchWine()
      }, []);
    
    return (
    ...
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search