Search code examples
reactjsreduxredux-sagaredux-thunk

redux-thunk: how to trigger on action?


I come from a background of working with react-saga, which has the concept of "effects" which lets us trigger action handlers in response to Redux actions being dispatched:

take('MY_ACTION', myActionHandler)

How would I go about doing the same thing with redux-thunk?


Solution

  • redux-thunk is a bit different concept than redux-saga. It's a simple middleware which allows you to create an action as a function (instead of an object) which can be run asynchronously (by default redux flow is synchronous).

    So for example you can easily make some async api call inside thunk and when it's done, dispatch final action object with api call result.

    That's it, there is no concept of subscribing to other redux actions like in the redux-saga. What you can do is to add your handler logic to the same place where your action is dispatched, but it can cause problems if there are more than one such places.

    Other solution (if you don't want to use redux-saga) could be writing your custom middleware which intercepts and handles particular actions.