1

I've written this piece of code using Hooks in React:

useEffect(() => {
  const runEffect = async () => {
    const data = await AsyncFunction();
    console.log('async operation')
  };
  runEffect();
});

useEffect(() => {
  console.log('useEffect-1')
});

useEffect(() => {
  console.log('useEffect-2')
});

The result is this: useEffect-1 useEffect-2 async operation

But I want to wait for async useEffect and then call another use effects, i.e. I want the expected result to be: async operation useEffect-1 useEffect-2

How it could be done?

regards

9
  • You have used async but there is no await Commented Sep 19, 2019 at 8:33
  • @Rajesh it is not important in result, with async or without it the result is what I wrote in the question Commented Sep 19, 2019 at 8:36
  • why const runEffect = async () => { since there's absolutely no Promises involved Commented Sep 19, 2019 at 8:37
  • @JaromandaX It is written in this way for simplicity, but the actual code returns a promise Commented Sep 19, 2019 at 8:39
  • Well, ok, have you searched for the phrase you used as the title of the question - some interesting reading Commented Sep 19, 2019 at 8:42

1 Answer 1

4
//Add 2 states
const [variable1, setVariable1] = useState(null);
const [variable2, setVariable2] = useState(null);

//Remove this out from useEffect
const runEffect = async () => {
  const data = await AsyncFunction();
  console.log('async operation');
  setVariable1(true); //Something that is not null
};

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

useEffect(() => {
  if (variable1) {
    console.log('useEffect-1');
    setVariable2(true); //Something that is not null
  }
}, [variable1]);

useEffect(() => {
  if (variable2) {
    console.log('useEffect-2');
  }
}, [variable2]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.