Home > other >  How can I use fetched data in next fetch with Axios?
How can I use fetched data in next fetch with Axios?

Time:11-12

How I can use data from my first fetch in second fetch ? I am getting undefined for the first search and then it's ok, how I can get it on first search without getting "undefined"?

  const [summoner, setSummoner] = useState("");
  const [playerData, setPlayerData] = useState({});
  const [playerRank, setPlayerRank] = useState({});

  function searchPlayer(event) {
    axios.get("API1"   summoner   API_KEY).then(function (response) {
      setPlayerData(response.data);
    }).catch(function (error) {
      console.log(error);
    });

    console.log(playerData.id);

    axios.get("API2"   playerData.id   API_KEY).then(function (response) {
      setPlayerRank(response.data)
    }).catch(function (error) {
      console.log(error);
    });
  }

This is my console:

log: undefined
log: id

CodePudding user response:

I believe in React JavaScript, Axios sends a call out to the server and then continues, so the console.log function is called before the server response has been received and the callback runs. You either need wait for the response with the await operator or the better solution is to place your second API call in the call back function. Then it will have the needed data for the second API call.

If you are working on the API as well, you might look at getting everything from the server in one API camp. This will involve working on the server side and I did not know from your post if you have access to the API end point coding. I hope this helps or gets you looking in the right direction.

CodePudding user response:

I recommend you to use something like useEffect to handle fetching data in react. Not sure what event is used for, but looked unused so if that's the case you can do the following:

  const [summoner, setSummoner] = useState("");
  const [playerData, setPlayerData] = useState({});
  const [playerRank, setPlayerRank] = useState({});

  function getPlayerData() {
    axios.get("API1"   summoner   API_KEY).then(function (response) {
      setPlayerData(response.data);
    }).catch(function (error) {
      console.log(error);
    });
  }

  function getPlayerRank() {
    if(!playerData.id) return;
    axios.get("API2"   playerData.id   API_KEY).then(function (response) {
      setPlayerRank(response.data)
    }).catch(function (error) {
      console.log(error);
    });
  }

  useEffect(() => {
    getPlayerData()
  }, [])

  useEffect(() => {
    getPlayerRank()
  }, [playerData])

This setup will trigger the getPlayerRank function any time playerData changes. If event is used in either request, you want to pass that into the dependency array as well so you would end up with

  useEffect(() => {
    getPlayerData(event)
  }, [event])

  useEffect(() => {
    getPlayerRank()
  }, [playerData])

https://reactjs.org/docs/hooks-effect.html

  • Related