B
B
baroman4ik2021-11-26 11:46:10
JavaScript
baroman4ik, 2021-11-26 11:46:10

How to wait for an async function to execute to change a state in React?

there is an asynchronous method that receives the date and there is a state array on which the rendering of everything else depends. how to wait for a response from getData in this case?

const App = async () => {
  const [noteArr, setNoteArr] = useState([])
  setNoteArr(getData())
  useEffect(() => {
    return () => {
      console.log(noteArr);
    };
  }, [noteArr]);
  return (
    <div className="App">
      <NoteInfo/>
      <NoteList noteArr={noteArr} setNoteArr={setNoteArr}/>
    </div>
  );
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denioo, 2021-11-26
@baroman4ik

Asynchronous functions must be called in useEffect in such a case. Put setNoteArr(getData()) in useEffect with empty dependencies [] and it will be called when the component is mounted.
Basically your component should look like this:

const App = () => {
  const [noteArr, setNoteArr] = useState([])

useEffect(() => {
    (async () => {
    const result = await getData();
setNoteArr(result);
   })()
  }, []);

  useEffect(() => {
    return () => {
      console.log(noteArr);
    };
  }, [noteArr]);
  return (
    <div className="App">
      <NoteInfo/>
      <NoteList noteArr={noteArr} setNoteArr={setNoteArr}/>
    </div>
  );
}

Then everything will work as it should and readability will improve

D
Dmitry Vorobyov, 2022-04-25
@CriticalError

Your answer is not entirely correct, since this method does not force you to wait for the execution of an asynchronous function if you put the debagger after

useEffect(() => {
    (async () => {
    const result = await getData();
setNoteArr(result);
   })()
  }, []);
then you can make sure that noteArr = []

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question