D
D
Demigodd2019-09-21 17:45:11
React
Demigodd, 2019-09-21 17:45:11

How to update one element in an Array in Redux?

There is an array Messages .

messages = [
  {
   _id: "111",
   text: "text1"
  },
  {
   _id: "222",
   text: "text2"
  },
]

In Redux during an action .
case UPDATE_MESSAGE:
  let foundIndex = state.messages.findIndex(message => message ._id == payload._id);
  state.messages[foundIndex] = payload;

    return {
    ...state,
    messages: [...state.messages]
  };

If this is how you directly change the current object that I already show in the frontend.
That pops up an error.
A state mutation was detected inside a dispatch, in the path...
What is the correct way to update one message in an array?
In general, is it necessary to do this, or would it be better to call the GetAllMessage method (which downloads all messages for the current room) via the socket for all users in the current room after the update.
But in this case, other users will download messages, and somehow it will not be clearer why the messages are downloaded.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
i1yas, 2019-09-21
@Demigodd

case UPDATE_MESSAGE:
  let foundIndex = state.messages.findIndex(message => message ._id == payload._id);
  state.messages[foundIndex] = payload;

    return {
    ...state,
    messages: [...state.messages]
  };

Redux is complaining because you are mutating the original state. And then for some reason you create a new array.
Correct like this:
case UPDATE_MESSAGE:
  let foundIndex = state.messages.findIndex(message => message ._id == payload._id);
  const messages = state.messages[foundIndex].slice(); // .slice() создаст копию массива
  messages[foundIndex] = payload;

    return {
    ...state,
    messages
  };

You need to return a new object (array) in which the changes were made.
You can't touch state directly

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question