Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Side effects in Redux reducer

Redux reducers should be without side-effects. But what if an action should trigger the download of a file in the browser where the content is based on the state of the store? Surely this should count as a side effect? Would something like the following be fine or should I be looking for alternative methods?

case 'SAVE_GRID': {
  const { json } = state
  fileDownload(json, 'data.json', 'application/json')
  return state
}
like image 864
damd Avatar asked Dec 15 '17 13:12

damd


2 Answers

Unless you have very complex state transitions, the actual fileDownload should happen in an action creator, not in the reducer. The reducer should be responsible for merging/reducing state and that is all.

action:

export const saveGrid = (json) => {
   return (dispatch) => {  
       fileDownload(json, 'data.json', 'application/json')
           .then(() => {
              dispatch({ type: 'SAVE_GRID', json });
           });
   }
}

reducer:

case 'SAVE_GRID': {
    return {
        ...state,
        json: action.json
    }
}
like image 149
Davin Tryon Avatar answered Sep 22 '22 10:09

Davin Tryon


There are libraries to handle such "side" effects.

For example:

  • redux-observables: they use RX observables under the hood.

https://redux-observable.js.org/docs/basics/Epics.html

  • redux-saga

https://redux-saga.js.org/

like image 33
Kev Avatar answered Sep 18 '22 10:09

Kev