Papucho
Papucho

Reputation: 123

implement the onSnapshot function for getting realtime updates in reactjs code

in my case I want to implement the onSnapshot function for getting realtime updates, so here's my sample code it's working now:

db.collection("Cities").onSnapshot((snapshot) => {

    snapshot.docs.forEach((doc) => {
         console.log(doc.data());
    });

});

But now, how can I implement it to the following code

 getMyInfo = () => {
        db.collection("Cities")
            .limit(8)
            .get()
            .then((docs) => {
                if (!docs.empty) {
                    let AllCities = [];
                    docs.forEach(function (doc) {
                        const city = {
                            id: doc,
                            ...doc.data(),
                        };
                        AllCities.push(city);
                    });
                    this.setState(
                        {
                            cities: AllCities,
                        },
                        () => {
                            this.setState({
                                isLoaded: true,
                            });
                        }
                    );
                }
            });
    };

Thanks

Upvotes: 0

Views: 73

Answers (1)

monsty
monsty

Reputation: 623

You are saving all your cities into your state. Use it to add or update the new (or updated) cities.

Maybe you can try something like that :

db.collection("Cities").onSnapshot((snapshot) => {
  snapshot.docs.forEach((doc) => {
    const updatedCity = doc.data();
    const cities = [...this.state.cities];
    const index = this.state.cities.findIndex(c => c.id === updatedCity.id);

    if (index >= 0) {
      cities[index] = updatedCity;
    } else {
      cities.push(updatedCity);
    }

    this.setState({ cities });
  });
});

Upvotes: 1

Related Questions