score:5

Accepted answer

you code is similar to what thunk does.

as per redux docs, actions should be pure. and they should always return same values for same input parameters. by using fetch you are allowing action to return not specific value, rather value from server and that mean action response may vary upon time.

that is called side effects. and it's something what shouldn't be in redux actions by default.

but why?

yes, you can type it inside action like you have, in small apps it does not matter.

in larger application there are benefits of using redux-saga:

  • actions are predictable, they just return payload like

    {
      type: 'fetch_posts',
      params: {
        category: 'programming'
      }
    }
    
  • and then you build middleware which will take actions with all data required to perform request to real api

possible advantages:

  • cleaner codebase (but may be overhead on smaller applications)
  • separation of "dummy" actions with all required information to perform requests and actual api middleware
  • request parameters are visible directly in redux dev tools
  • possible to easily debounce, throttle fetches which may be really tricky with redux-thunk
  • possible to easily combine actions (wait for another event/fetch, chain events)
  • possible to stop running tasks

from personal experience, on one project (larger codebase) we have started with redux-thunk, but later we needed to integrate more advanced features, like throttle, and some dependencies between actions. so we rewrote everything to redux-saga and it worked well for us.

score:1

you are kind of replicating redux-thunk here. a pure redux action creator should return an action object to be dispatched and not dispatch an action itself (see redux doc on action creator).

to better understand why your technic is a replication of redux-thunk, look at this post from its author


Related Query

More Query from same tag