skip to Main Content

I want to do something after calculateWinner() performed whenever a certain variable changed. Because calculateWinner() function can change the value of some variables that are related what I want to do.

So, I coded like as:

  useEffect(async () => {
    await calculateWinner();
    setCurrentMove(currentMove + 1);
  },[history])

But,

the terminal says:

Effect callbacks are synchronous to prevent race conditions.

What can I do to get the values that are changed by calculateWinner()function, then with these I do next operation whenever a certain variable changed?

2

Answers


  1. Chosen as BEST ANSWER

    I found answer to this question.

    useEffect(() => {
      async () => {
        const response = await calculateWinner();
      }
      setCurrentMove(currentMove + 1);
    }, [history]); 
    

  2. You can’t use await function in useEffect.

    To solve this problem, you can do like below.

    useEffect(() => {
      (async () => {
        await calculateWinner();
        setCurrentMove(currentMove + 1);
      })();
    }, [history]);
    

    Also, you can define async function and use it.

    const func = async () => {
      await calculateWinner();
      setCurrentMove(currentMove + 1);
    };
    
    useEffect(() => {
      func();
    }, [history]);
    

    I think this answer can help you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search