0

I'm building an angular website. Normally I made backend call in onInit method and store the data in an component state. Now I want to add redux to my website. Should I just raise action on the onInit method and make the actual backend call in redux reducer or should I make backend call in my component onInit method and add the data to redux state later on? Which one is the right way to do? I heard that redux reducer should be pure functions so is doing backend call make the function inpure?

Haha
  • 148
  • 1
  • 8

2 Answers2

1

You should not make a backend call in a reducer. Redux docs say:

The reducer is a pure function that takes the previous state and an action, and returns the next state

And:

No side effects. No API calls. No mutations. Just a calculation.

Side effects in Redux can be done via redux-thunk, redux-saga, or making side-effect calls in plain Redux middleware.

Of those options, redux-thunk is easiest to get started with. It lets you do async/side-effects in the actions.

// store.js
import thunk from 'redux-thunk';
const myReduxStore = createStore(myRootReducer, applyMiddleware(thunk));
// actions.js
const myAction = (someArg) => {
  return dispatch => {
    myApiCall().then(result => {
      dispatch({ type: 'YAY_SUCCESS', result })
    })
  }
}

Then when you dispatch the action

dispatch(myAction())

The async side-effect will occur after the dispatch call but before the reducer picks up the action.

brietsparks
  • 4,776
  • 8
  • 35
  • 69
0

Yes, you should not make api calls in reducer as they should be pure and free from any side effects.

Should I make backend call in my component onInit method and add the data to redux state later on?

I would suggest going by this approach.

kooskoos
  • 4,622
  • 1
  • 12
  • 29