skip to Main Content

I am trying to use the data that loadsummoner sets into a state that will hold the json object returned but when trying to call the second function I am getting undefined when making my api call but on the next render it populates the state that the second function updates.

    useEffect(() => {
    try {
      if (Object.keys(results).length === 0) {
        loadSummonerData();
      }
    } catch (err) {
      console.log(err);
    }
    return function cleanup() {
      setResults({});
    };
  }, []);

   useEffect( async() => {
    try {
      if (Object.keys(results).length != 0) {
        await setStats(results.id)
    }
    } catch (err) {
      console.log("error");
    }
    return function cleanup() {
       setStats({});
    };
   }, [results]);

I have tried a few different ways to accomplish this like placing the first function call in the second function declaration with await but still reaching an undefined state on mount

The function setStats should take in an id from a json object contained in the state set by the loadSummonerData function.

2

Answers


  1. Chosen as BEST ANSWER

    put everything in the first function call made in the first useeffect!


  2. Do not set an async function in useEffect!

    instead of useEffect( async() => {..., try replace with

    useEffect(()=> {
    
    (async() => {
        try {
          if (Object.keys(results).length != 0) {
            await setStats(results.id)
        }
        } catch (err) {
          console.log("error");
        })()
    
        return function cleanup() {
           setStats({});
        };
       }, [results]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search