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

Pezhman Parsaee
  • 1,209
  • 3
  • 21
  • 35

1 Answers1

3
//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]);
Luka Dumančić
  • 116
  • 1
  • 8