Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux: data manipulation is a responsability of the action or of the reducer?

My action fetch an url and got a json.

I need to transform this json into an array of objects and set into the state.

I ask you: Where must placed the business logic to transform json into an array of object?

Must be placed

  1. into the action code dispatching an action with a 'ready-to-use' payload,

or

  1. into the reducers code, which receive the 'raw data' as json in the payload, then transform into an array of objects and put into the state

?

like image 550
realtebo Avatar asked Nov 01 '17 08:11

realtebo


2 Answers

According to the Redux doc

Actions are payloads of information that send data from your application to your store.

Actions describe the fact that something happened, but don't specify how the application's state changes in response. This is the job of reducers.

So I will go for the option #2: doing it into the reducers code, which will receive the 'raw data' as json in the payload, then transform into an array of objects and put into the state.

like image 118
juanlumn Avatar answered Nov 11 '22 02:11

juanlumn


This is an old question, but i would like to share my thoughts. Your situation is referred to as an async action in the redux documents. And while:

Actions are payloads of information that send data from your application to your store.

Actions describe the fact that something happened, but don't specify how the application's state changes in response. This is the job of reducers.

Async actions are a little more complex and as shown in the redux documentation under Advanced Tutorials: Redux Async Actions:

export const RECEIVE_POSTS = 'RECEIVE_POSTS'

function receivePosts(subreddit, json) {
  return {
    type: RECEIVE_POSTS,
    subreddit,
    posts: json.data.children.map(child => child.data),
    receivedAt: Date.now()
  }
}

They suggest you parse the async response before you send it to the reducer. So i think option 1 is the correct one.

Hope this helps!

like image 28
Nick Pelov Avatar answered Nov 11 '22 04:11

Nick Pelov