简体   繁体   中英

Ionic React + FIrebase. When updating a data in firebase. Loop items are populated twice

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>

When the data changes, your on() callback is called again with a complete snapshot of the data for the query. Since you declare `` outside of the callback, you end up adding the new data after the previous data, which is why you see both sets of data in your UI.

The solution is to always start with a new array:

  useEffect( () => {
    console.log('Enter')
    firebase.database().ref('users').orderByChild('type').equalTo('doctor').on('value',(snapshot)=>{
      let key;
      let newArr = []
      snapshot.forEach( (childSnap) => {
        key = childSnap.key
        const snapVal = snapshot.val();
        newArr.push(snapVal[key])
      })
      setDoctor(newArr)
    })
  }, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM