kxh
kxh

Reputation: 59

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?

Upvotes: 0

Views: 337

Answers (2)

sohaieb azaiez
sohaieb azaiez

Reputation: 780

the function getEvaluationsQuestionsByOrganizations(..) is defined as async function, but you are using it synchronously, in that case you should call your codes as below:

useEffect(() => {
 const fetchedDataAPI = async () => {
    return await getEvaluationsQuestionsByOrganizations();
 };

 fetchedDataAPI
  .then(res => { evAnswers();})
  .catch(err => {..});
;

}, []);

Upvotes: 1

Semyon Kirekov
Semyon Kirekov

Reputation: 1442

Try adding another useEffect hook that depends on evQuestion state.

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

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

Upvotes: 2

Related Questions