Can't update state after reloading the app in react native firebase?

后端 未结 1 1230
醉梦人生
醉梦人生 2021-01-16 09:07

I have some issues with Firebase in React Native.

I\'m tried to read the data from the Realtime database. I get the data from database and set them into the state an

相关标签:
1条回答
  • 2021-01-16 09:32

    I think your database listener should look more like this:

    const providerRef = firebase.database().ref('providers');
    providerRef.on('value', snapshot => {
        var newState = [];
        console.log(snapshot.val());
        snapshot.forEach((childSnapshot) => {
            newState.push({
                id: childSnapshot.val().id,
                username: childSnapshot.val().username,
                coordinates: {
                    longitude: childSnapshot.val().coordinates.longitude,
                    latitude: childSnapshot.val().coordinates.latitude,
                }
            });
        });
        this.setState({ providers: newState })
    });
    

    Changes from yours:

    • Declare newState inside the callback, so that you start out with an empty array each time you get data from Firebase.
    • Call setState(...) only after processing all data from the database, instead of after each item.
    0 讨论(0)
提交回复
热议问题