Search code examples
reactjsfirebaseuse-effect

React fetching data twice


I am trying to fetch some data from google's firestore in an useEffect, and saving it in useState variable

useEffect(() => {
    const fetchFirst = async () => {
        ...
        // setting the new found data in a useState
        setData1(data1)
    }
    fetchFirst()
}, [])

Now, I want to fetch some other data from firestore, but this data requires some information from previous fetched (fetchFirst) data. I tried to do this but does not work

useEffect(() => {
    const fetchFirst = async () => {
        ...
        // setting the new found data in a useState
        setData1(data1)
    }
    const fetchSecond = async (data1) => {
        ...
        // setting the new found data in a useState
        setData2(data2)
    }
    fetchFirst()
    fetchSecond(data1)
}, [])

My first fetch works completely fine, but when my code reaches the second fetch, the input data (data1) is null. Can someone please help me figure it out. Thanks


Solution

  • If your using async you should wait, with the await keyword, for the first fetching to finish, then use its result in the fetchSecond:

    useEffect(() => {
      const fetchFirst = async (): SomeData => {
        const data = await fetch(...);
        return data;
      };
    
      const fetchSecond = async (data: SomeData) => {
        await fetch(...);
      };
    
      const fetchAllData = async () => {
        const data = await fetchFirst();
        await fetchSecond();
      };
    
      fetchAllData();
    }, []);