I am trying to fetch the data from firebase using useEffect in React JS, But my problem is its not updating / rendering the page automatically when Any changes in database occurs.
I Tried
const [users,setUsers]=useState([]);
const usersCollectionRef=collection(db,"customers");
useEffect(()=>{
const getUsers=async ()=>{
const data=await getDocs(usersCollectionRef);
setUsers(data.docs.map((doc)=>({...doc.data(),id:doc.id})))
};
getUsers();
console.log(users)
},[])
and here returning the data
return (
<div className="App">
{users.map((user)=>{
return <h1 key={user.id}>{user.id}</h1>
})}
</div>
)
Please help me with this
Just use onSnapshot. It will update on every changes in collection. So, Answer
useEffect(() => {
onSnapshot(usersCollectionRef, (snapshot) =>
setUsers(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
)
}, [])