I have a function that gets all the data in firebase realtime database and putting it inside an array in order to map in react. But when I do an update,add. It just doubles the list but when i switch to other tabs and go back again, It will return the original data with the correct number of items in it. Can someone tell me what did I do wrong about this?
Here is my data when I enter the component
When I do an update in firebase here is the result, Also the UI isnt updated sometimes. I need to switch tabs in order to make the changes happen.
Here is my code in retrieving data and the loop.
const [doctors, setDoctor] = React.useState([]);
useEffect( () => {
console.log('Enter')
let newArr = []
firebase.database().ref('users').orderByChild('type').equalTo('doctor').on('value',(snapshot)=>{
let key;
snapshot.forEach( (childSnap) => {
key = childSnap.key
const snapVal = snapshot.val();
newArr.push(snapVal[key])
})
setDoctor(newArr)
})
}, [])
In the loop:
<IonList>
{doctors.map((elem, index) => {
// index has to come from the second parameter from map
console.log(doctors)
return (
<IonItem key={index}>
<IonLabel>
<IonText className="font-weight: bold;">
<h3>{elem["name"]}</h3>
</IonText>
<h4>{elem["speciality"]}</h4>
<h4>{elem["email"]}</h4>
</IonLabel>
<br></br>
</IonItem>
);
})}
</IonList>

