Ad

Code Block Runs Before Api Call Gets A Response

- 1 answer

The second useEffect block runs before the first has received any data back. This causes the second block to return an error and an empty array.

I've tried using async/await, as this has solved problems like this for me in the past. However, it doesn't seem to have an effect here.

    const [session, setSession] = useState("");
    const [champions, setChampions] = useState([]);

    useEffect(() => {
        axios.get(`http://api.paladins.com/paladinsapi.svc/createsessionJson/${devId}/${generateSignature('createsession')}/${moment.utc().format('YYYYMMDDHHmmss')}`).then((response) => {
            setSession(response.data.session_id);
            console.log(session);
        }).catch((error) => {
            console.log(error);
        })
    }, [])

    useEffect(() => {
        axios.get(`http://api.paladins.com/paladinsapi.svc/getchampionsJson/${devId}/${generateSignature('getchampions')}/${session}/${moment.utc().format('YYYYMMDDHHmmss')}/1`).then((response) => {
            setChampions(response.data);
            console.log(champions);
        }).catch((error) => {
            console.log(error);
        })
    }, []);

It should return an array of objects to champions, but since it doesn't receive a session id, the api call is not the correct address keeping champions as an empty array.

Ad

Answer

useEffect is an asynchronous function so you need to just move the calls both into one useEffect function and then call your api's synchronously. I would move this into a separate function and use async/await to run your api call synchronously. Then call that function in your useEffect function like so:

useEffect(() => {
  getData();
},[]);

const getData = async () => {
  try{
    const session = await axios.get(`your first call here`);
    const champions = await axios.get(`your second call here`);

    setSession(session.yourData);
    setChampions(champions.yourData);
  }catch(err){
    console.log(err);
  }
} 

If you have data from the first api call that the second one uses then you don't need to set that to any state object you can just use it directly in your second api call.

Ad
source: stackoverflow.com
Ad