I am learning React and learned some basics, so I used this knowledge to make this basic project. I'm making a simple note-saving app using React and Firebase.
The data is transferred to the Firebase database flawlessly.
Get data.
The problem I am facing is that the data fetched is not updated in the UI.
import { useEffect, useState } from 'react'; import { AiFillCaretUp } from 'react-icons/ai'; import './Card.css'; export default function Card(props) { const [showPara, setShowPara] = useState(false); const [data, setData] = useState([]); console.log('inside card'); useEffect(() => { let notesData = []; console.log('inside UseEffect'); 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 }); } }; fetchNote(); // console.log(notesData); setData(notesData); }, []); const toggleHandler = () => { setShowPara((preVal) => !preVal); }; const paraClass = showPara ? 'card-para toggle' : 'card-para'; const rotate = showPara ? 'icon rotate' : 'icon'; return ( {console.log('inside card container', data)} {data.map((card) => ( {card.title}
{card.note}
))} ); }
Show data here
{console.log('inside card container', data)}
But it doesn’t work
{data.map((card) => ())}{card.title}
{card.note}
I hope you understand the problem.
One way is to write like this:
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 usesetData(notesData)
immediately after callingfetchNote()
, the data is not ready yet.Oryou 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: