mangocaptain
mangocaptain

Reputation: 1495

React redux architecture: where to do data organization - action or store or component?

I'm learning to build a pokemone app that hits the pokemon api, which gives you a lot more info then you need. I'm having trouble figuring out where I should put my code that sifts out the only info I need for my app.

For example, fetching a pokemon's type will return you a type object that looks like this:

{pokemon: [...], weakAgainst: [...]}

If this is what is the data that I'm getting back from my ajax request, and I only want the pokemon array, should

  1. I sift this out in the success of the ajax call that is in my actionsCreators.js and then return that to be dispatched to the store? or

  2. dispatch all of the data type object to my reducer and then in my reducer.js file sift out the pokemon array and copy it to my state? or

  3. copy the whole data object to my state and then sift out the pokemone array in my component's props (that was passed down from mapStateToProps)?

I'm thinking it should be in the reducer? Because it's job is to reduce data to what you need and move it on to the state?

Upvotes: 0

Views: 199

Answers (1)

james emanon
james emanon

Reputation: 11807

I am of the mind that you should hand the reducer what it needs, if you have the means. Inevitably, you will need to massage and manipulate data in the reducer, but if you can minimize it, I would. Your reducer should be a pure function -- no side effects, the reducers always returns same output given same input etc.. I like to reduce "side effects" by giving the reducer exactly what it needs, especially since the data you need to handoff is so nicely handed to you.. ala.

your actionCreator

export function getPokemanApiData() {
  return dispatch => {
    axios.get(APIS.getPokemanURL)
      .then((response) => {
        dispatch(getSuccess(response))
      })
      .catch((err) => {
        dispatch(getError(err))
      })
  }
}

function getSuccess(response) {
   return {
      type: TYPES.MY_POKEMAN_TYPE,
      payload: response.pokemon

   }
}

reducer

case TYPES.MY_POKEMAN_TYPE:
   return {
      ...state,
      pokemonData: action.paylod
   }

So, the way I see it - try to reduce side effects, minimize the amount of work the reducer has to do. Makes things easier to test too. In the example above, the reducer has exactly what it needs, returns a new state without much fuss. I've read others code in which they like to do the lifting in the reducer, not me. I'd like to hear what others say.

Upvotes: 1

Related Questions