简体   繁体   中英

Which Life Cycle method to use of React while getting data from Database using Socket IO

I'm storing data in a database and whenever it updates, It sends an event to the client side.

Here is server-side

socket.on("note delete", function(data) {
    rooms
      .findOneAndUpdate(
        {
          _id: data.roomId
        },
        { $pull: { notes: { _id: data._id } } }
      )
      .then(docs => {
        rooms.find({ _id: data.roomId }, function(err, docs) {

          socket.emit("remainingnotes", docs);
        });
      })
      .catch(err => {
        console.log("err", err.stack);
      });

remainingnotes is emitted on the client side. Now I want to update its content to this.state/MobX state real-time. as soon as database changes, I want my Store value to update accordingly.

How can I do this?

// Client Side
socket.on("remainingnotes", function(data) {
      ChatStore.msgs = data[0].conversation; // ChatStore is my MobX store.
    });

I've tried adding this event in Constructor and in ComponentDidMount but both didn't update. Is there any way to listen to events on the client side for React?

The data layer should be separate from the React layer, which is really a view layer.

With React + MobX, you'll do something like this:

MOBX STORE:

  • connects to websocket / manages connection
  • receives UI events from view/React layer
    • updates store or
    • sends websocket events (depending on the UI event)
  • receives events form websocket and updates store accordingly

REACT COMPONENT:

  • receives props from MobX store whenever data changes
  • sends events to MobX store

So the React component neither knows nor cares where the MobX store data comes from, it simply re-renders when the data changes and sends UI events to the store.

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