Answer the question
In order to leave comments, you need to log in
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
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>
);
}
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 questionAsk a Question
731 491 924 answers to any question