Reactjs with rails action cable state management

Viewed 12

I am using action cables in rails. I have single cable in Reactjs. I am able to update compulSoryData state via dispatch under data.status == created condition but I am getting initial state of compulSoryData reducer under data.status == update. It seems like created portion is appending data successfully but update portion is unable to update as I am getting old initial state of my reducer. I am unable to figure out problem and it seems to me that problem lies within this subscription.create portion as my reducers and appending and updating states successfully elsewhere.

const StatusChannel = () => {
    cable.subscriptions.create(
      {
        channel: `StatusChannel`,
      },
      {
        connected: () => {
          console.log("StatusChannel connected!");
        },
        disconnected: () => {
          console.log("StatusChannel disconnected!");
        },
       received: (data) => {
          if (data.status === "created") {
            dispatch(appendCompulsoryData(data));
          } else if (data.status === "update") {
            console.log(compulsoryData);
          }
        },
      }
    );
  };
1 Answers

It will not let you updated the current version of data. Try to store data in another array or object then make changes in that object (as an update to state) and then assign it to the actual state value.

Here is the algo: (if data is an array):

let updatedarray = [...stateArray]
// change in updatedarray
//assign it to the reducer of state
Related