Search code examples
redux

Is it ok to make backend call using reducer in redux?


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?


Solution

  • 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.