0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.