Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to wait async data to start sync function

I get some data from an api call and set them in a state. Then I use this state variable in another function to filter some data. When the user opens the interface for the first time the data doesnt show because the sync function gets the empty data from the state.

Here is the code :

const [evQuestion, setEvQuestion] = useState();
const [answers, setAnswers] = useState();

const getEvaluationsQuestionsByOrganizations = async (evalId) => {
    const response = await apiStandarts.get(`/evaluation-questions?organization_evaluation=${evalId}`);
    setEvQuestion(response.data);
  };

  const evAnswers = () => {

    const evAnswers = questions.map(q => {
        return evQuestion?.map(ev => {
          return q.question_options.find(i => i.id === ev.questOptionId)
        });
      });
      const filterAnswers = evAnswers.map(q => {
        return q?.filter(Boolean)
      })
      const answersToObject = filterAnswers.map(item => {
        return convertArrayToObject(item)
      });
      const arr = {...answersToObject}
    const obj2 = Object.fromEntries(
      Object.entries(arr).map(([key, value]) => [key, value])
    )
     const obj3=  Object.values(obj2).map(item => {
        return {[item.question]: {...item}}
      })
      const savedAnswers = convertArrayToObject(obj3);
      console.log(savedAnswers)
      setAnswers(savedAnswers)
    }

useEffect(() => {
 getEvaluationsQuestionsByOrganizations();
 evAnswers();
}, [])

I’ve tried to wrap the evAnswers function in a settimeout function but with no luck. How can I achieve this, any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try adding another useEffect hook that depends on evQuestion state.

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

useEffect(() => {
 evAnswers();
}, [evQuestion]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading