Home > Software engineering >  How to guarantee that data from 'fetch' is present
How to guarantee that data from 'fetch' is present

Time:09-03

I am doing something like this, where I retrieve the data of a fund which contains an id, then I query the server again using the retrieved id to retrieve data from another table:

const [backendData, setBackendData] = useState({})
const [fundData, setFundData] = useState({})

useEffect(() => {
  async function fetchFund(){
      console.log("fetching fund...");
      var query = getQueryVariable('fund');

      await fetch(`http://localhost:24424/api/funds?fund=${query}`).then(
          response => response.json()
      ).then(
          data =>{
              setBackendData(data);
          }
      )
  }

  async function fetchData(){
      var fundId = backendData[0]?._id ?? "fundid";

      await fetch(`http://localhost:24424/api/funds/data?id=${fundId}`).then(
          response => response.json()
      ).then(
          data =>{
              setFundData(data);
          }
      )
   }

   fetchFund();
   fetchData();
}, [])

The problem is that in the fetchData() function, fundId is always equal to the fallback value fundid when the page first loads, so the server query fails. When using {fundId} later on in the page, it works fine as the value is eventually retrieved. How can I tell React to wait for backendData[0]?._id to be present before executing the fetchData() function?

CodePudding user response:

You should separate the two function so one depend of the existing of the other your code will look something like this

const [backendData, setBackendData] = useState({})
const [fundData, setFundData] = useState({})

useEffect(() => {
  async function fetchFund(){
      console.log("fetching fund...");
      var query = getQueryVariable('fund');

      await fetch(`http://localhost:24424/api/funds?fund=${query}`).then(
          response => response.json()
      ).then(
          data =>{
              setBackendData(data);
          }
      )
  }
   fetchFund();
}, [])


useEffect(() => {

    if(!backendData?.[0]?._id) return;
    
    async function fetchData(){
        var fundId = backendData[0]?._id ?? "fundid";
  
        await fetch(`http://localhost:24424/api/funds/data?id=${fundId}`).then(
            response => response.json()
        ).then(
            data =>{
                setFundData(data);
            }
        )
     }

   fetchData();

}, [backendData])

Now fetchData will only get called when at least one backendData is available

  • Related