Shashika Virajh
Shashika Virajh

Reputation: 9477

Rerender screen after updating redux state in react-native

In my application, after updating a row of a flatlist from redux state, it did not rendered as expected.

my code was

   // like Button Handler
    case SM_ACTION_LIKE:
      let updatedPosts = state.posts;

      updatedPosts.forEach(post => {
        if (post.shareId === action.payload.postId) {
          post.likeCount = action.payload.likeCount
        }
      });

      return {
        ...state,
        posts: updatedPosts
      };
      break;

After trying to find a solution to this issue, I used the following code, and it works as expected.

// like Button Handler
case SM_ACTION_LIKE:
  let updatedPosts = state.posts;

  updatedPosts.forEach(post => {
    if (post.shareId === action.payload.postId) {
      post.likeCount = action.payload.likeCount
    }
  });

  return {
    ...state,
    posts: updatedPosts.slice()
  };
  break;

Use of slice() at the end of the updatedPosts was the solution. Is this a good practice or what can be a better way to handle this?

Upvotes: 1

Views: 115

Answers (1)

agenthunt
agenthunt

Reputation: 8678

The reason why this works is updatedPosts.slice() returns a copy of posts which is what redux expects updates to state needs to be immutable.

The usual way to do this without using any immutable libraries would be using the spread operator

  return {
    ...state,
    posts: [...updatedPosts]
  };

The other ways would be to use immutable libraries like Immutablejs, immer etc

Upvotes: 2

Related Questions