Redux reducer to fetch, like, and dislike posts

Viewed 1288

I have made a like functionality with Redux and React Native.

I have a reducer with initial state posts = [] and my reducer looks like

const initialState = {
  posts: []
};

function postReducer(state = initialState, action) {
  switch (action.type) {
    case FETCH_POSTS:
      return {
        ...state,
        posts: action.posts
      };

    case LIKE_POST:
      return {
        ...state,
        posts: state.posts.map(post => {
          if (post._id === action.postId) {
            return {
              ...post,
              likes: !!post.likes ? post.likes.concat(action.userId) : [action.userId]
            }
          }
          return post;
        })
      };

    case UNLIKE_POST:
      return {
        ...state,
        posts: state.posts.map(post => {
          if (post._id === action.postId) {
            return {
              ...post,
              likes: post.likes.filter(userId => userId !== action.userId)
            }
          }
          return post;
        })
      };

    default:
      return state
  }
};

I know that I can not mutate the posts array in my state, so I have to return a new array of posts where I have modified the post that a user tries to like/unlike.

It seems to work very well, but it's daunting slow. I only have very few posts, but I still have to wait almost a second for it the like to be visible.

Is this the right approach? Am I storing my posts correctly as a simple array in the state? I'm not sure what the alternative is, but I have, for instance, seen in this GitHub repo that it can be done different, although I don't fully understand the structure of it.

1 Answers
Related