score:5

Accepted answer

make the second call inside a .then chained to the end of the first promise chain ... in simple terms, chain your promises

something like

useeffect(() => axios.get(`firsturl`)
    .then(response => {
        setcasesheaderfields(response.data.result.fields);
        return response.data.result.fields;
    })
    .then(casesheaderfields => axios.get(`url${casesheaderfields}`))
    .then(response => {
        setcasesfields(response.data.result.record_set);
    }), []);

score:1

you can write something like this:

  useeffect(() => {
      return axios
        .get(`firsturl`)
        .then(response => {
          return response.data.result.field
        }).then(result => { 
         return axios.get(`url${result}`)
        });
   });

with async / await :

  useeffect(async () => {
      const result1 = await axios
        .get(`firsturl`)
        .then(response => {
          return response.data.result.field
        });
      const result2 = await axios.get(`url${result1}`)
      return result2 
   });

score:2

you can use async/await to relieve the mess.

useeffect(async () => {
    const response = await axios.get(`firsturl`)
    const result = await axios.get(`url${response.data.result.fields}`)
    console.log(result.data)
})

score:3

the queries result1 and result2 look sequential but there are simultaneous. in other words, result2 doesn't wait for result1 to finish before being executed.

here is a working example to chain promises using async/await:

useeffect(async () => {
  try {
    // make a first request
    const result1 = await axios.get(`firsturl`);
    setcasesheaderfields(result1.data.result.fields);

    // use resutlt in the second request
    const result2 = await axios.get(`url${"some params from result1"}`);
    setcasesfields(result2.data.result.record_set);
  } catch (e) {
    // handle error here
  }
}, []);

edit

based on comments, here is a best way to use async with useeffect without warning in the console:

useeffect(() => {
  const fetchdata = async () => {
    try {
      // make a first request
      const result1 = await axios.get(`firsturl`);
      setcasesheaderfields(result1.data.result.fields);

      // use resutlt in the second request
      const result2 = await axios.get(`url${casesheaderfields}`);
      setcasesfields(result2.data.result.record_set);
    } catch (e) {
      // handle error here
    }
  };

  fetchdata();
}, []);

score:8

you can chain the results as they are regular promises: ref

axios.get(...)
  .then((response) => {
    return axios.get(...); // using response.data
  })
  .then((response) => {
    console.log('response', response);
  });

Related Query

More Query from same tag