One way is to write like this:
useEffect(() => { let notesData = []; const fetchNote = async () => { const response = await fetch('https://notes-keeper-react-default-rtdb.firebaseio.com/notes.json'); const data = await response.json(); for (const key in data) { notesData.push({ id: key, title: data[key].title, note: data[key].note }); } setData(notesData); // 在這里數(shù)據(jù)已經(jīng)準(zhǔn)備好了 }; fetchNote(); }, []);
fetchNote
is an asynchronous function, so it takes some time to complete the task and get the data. Therefore, you should wait for the data to be ready, unfortunately when you use setData(notesData)
immediately after calling fetchNote()
, the data is not ready yet.
Or you can return the data inside the async function and automatically return another promise that resolves to the required data, and then you can update your data:
useEffect(() => { let notesData = []; const fetchNote = async () => { const response = await fetch('https://notes-keeper-react-default-rtdb.firebaseio.com/notes.json'); const data = await response.json(); for (const key in data) { notesData.push({ id: key, title: data[key].title, note: data[key].note }); } return notesData; // 返回一個解析為 'notesData' 的 promise }; fetchNote() .then((updatedData) => { setData(updatedData); }) }, []);