Using axios response data in another axios request

Viewed 1355

I'm using axios to fetch information, and I need that information in another handler of a different axios response. I can't seem to be able to use the data loaded in the first response in the second response handling.

For example:

const [firstData, setFirstData] = useState({});
const [secondData, setSecondData] = useState({});

await axios.get("url/firstRoute").then((response) => {
    setFirstData(response.data);
}).then(async () => {
    await axios.get("url/secondRoute").then((response) => {
        setSecondData(firstData); // firstData is still an empty Object here for some reason
    })
});

How can I make sure firstData isn't empty when I'm in the second request? I also tried using the useEffect hook for firstData, and inside it calling the second axios request, but I still get the same outcome of firstData being empty. (Assume that both requests return data)

1 Answers

You can just return value back from the first .then like this:

await axios
  .get('url/firstRoute')
  .then((response) => {
    setFirstData(response.data);
    return response.data;
  })
  .then(async (firstData) => {
    await axios.get('url/secondRoute').then((response) => {
      setSecondData(firstData); // firstData is still an empty Object here for some reason
    });
  });

In your code you are setting state but it is not done before your then clause.

Related