Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to guarantee that data from 'fetch' is present

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading