Search code examples
reactjsreact-reduxredux-thunk

In redux, is altering data in an action good practice?


I'm a beginner still getting to grips with redux and would like to know whether the way I'm handling data in my action creator is good practice or not.

I'm building an app that fetches posts from reddit. The action creator fetchPosts gets the data from reddit, and then filters out stickied posts and limits the number of posts dispatched to the reducer.

export const fetchPosts = (subreddit) => async (dispatch) => {
  const res = await fetchReddit.get(`/r/${subreddit}.json`);
  const postsArray = res.data.data.children;
  //filter out any stickied posts in array
  const postsWithstickiedRemoved = postsArray.filter(post => !post.data.stickied);
  dispatch({ type: FETCH_POSTS, payload: postsWithstickiedRemoved.slice(0, 21) })
}

Is this good practice, or should I dispatch res.data to the reducer and manipulate it there? Does it even matter??

Thanks


Solution

  • If we refer to the official redux documentation:

    actions are plain JavaScript objects that have a type field.

    So in your case, the action is

    { type: FETCH_POSTS, payload: postsWithstickiedRemoved.slice(0, 21) }.
    

    Your fetchPosts function is a service, not an action, and it's totally ok to manipulate data in a service.