Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put synchronous side effects linked to actions in redux?

(Note: My question was not clearly written, and I was thinking about some things wrong. The current version of the question is just an attempt to write something that could make the accepted answer useful to as many people as possible.)

I want to have an action that adds an item to a store and registers it with an external dependency.

I could use the thunk middleware and write

export function addItem(item) {
  return dispatch => {
    dispatch(_addItemWithoutRegisteringIt(item));
    externalDependency.register(item);
  };
}

But the subscribers would be notified before the item was registered, and they might depend on it being registered.

I could reverse the order and write

export function addItem(item) {
  return dispatch => {
    externalDependency.register(item);
    dispatch(_addItemWithoutRegisteringIt(item));
  };
}

But I track the item in the external dependency by a unique id that it is natural to only assign in the reducer.

I could register the item in the reducer, but I am given to understand that it is very bad form to do side effects in a reducer and might lead to problems down the line.

So what is the best approach?

(My conclusion is: there are a number of approaches that would work, but probably the best one for my use case is to store a handle into the external dependency in Redux rather than a handle into Redux in the external dependency.)

like image 227
gmr Avatar asked Oct 07 '15 01:10

gmr


People also ask

Should Redux actions have side effects?

However, Redux's middleware makes it possible to intercept dispatched actions and add additional complex behavior around them, including side effects. In general, Redux suggests that code with side effects should be part of the action creation process.

Are Redux actions synchronous?

Introduction. By default, Redux's actions are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects. Redux also allows for middleware that sits between an action being dispatched and the action reaching the reducers.

How do you handle async actions in Redux?

Redux Async Data Flow​ Just like with a normal action, we first need to handle a user event in the application, such as a click on a button. Then, we call dispatch() , and pass in something, whether it be a plain action object, a function, or some other value that a middleware can look for.

Which of the following functions can be used to dispatch actions in Redux?

You can dispatch an action by directly using store. dispatch(). However, it is more likely that you access it with react-Redux helper method called connect(). You can also use bindActionCreators() method to bind many action creators with dispatch function.


2 Answers

If you use Redux Thunk middleware, you can encapsulate it in an action creator:

function addItem(id) {
  return { type: 'ADD_ITEM', id };
}

function showNotification(text) {
  return { type: 'SHOW_NOTIFICATION', text };
}

export function addItemWithNotification(id) {
  return dispatch => {
    dispatch(addItem(id));
    doSomeSideEffect();
    dispatch(showNotification('Item was added.');
  };
}

Elaborating, based on the comments to this answer:

Then maybe this is the wrong pattern for my case. I don't want subscribers invoked between dispatch(addItem(id)) and doSomeSideEffect().

In 95% cases you shouldn't worry about whether the subscribers were invoked. Bindings like React Redux won't re-render if the data hasn't changed.

Would putting doSomeSideEffect() in the reducer be an acceptable approach or does it have hidden pitfalls?

No, putting side effects into the reducer is never acceptable. This goes against the central premise of Redux and breaks pretty much any tool in its ecosystem: Redux DevTools, Redux Undo, any record/replay solution, tests, etc. Never do this.

If you really need to perform a side effect together with an action, and you also really care about subscribers only being notified once, just dispatch one action and use [Redux Thunk] to “attach” a side effect to it:

function addItem(id, item) {
  return { type: 'ADD_ITEM', id, item };
}

export function addItemWithSomeSideEffect(id) {
  return dispatch => {
    let item = doSomeSideEffect(); // note: you can use return value
    dispatch(addItem(id, item));
  };
}

In this case you'd need to handle ADD_ITEM from different reducers. There is no need to dispatch two actions without notifying the subscribers twice.

Here is the one point I still definitely don't understand. Dan suggested that the thunk middleware couldn't defer subscriber notification because that would break a common use case with async requests. I still don't understand this this.

Consider this:

export function doSomethinAsync() {
  return dispatch => {
    dispatch({ type: 'A' });
    dispatch({ type: 'B' });
    setTimeout(() => {
      dispatch({ type: 'C' });
      dispatch({ type: 'D' });
    }, 1000);
  };
}

When would you want the subscriptions to be notified? Definitely, if we notify the subscribers only when the thunk exits, we won't notify them at all for C and D.

Either way, this is impossible with the current middleware architecture. Middleware isn't meant to prevent subscribers from firing.

However what you described can be accomplished with a store enhancer like redux-batched-subscribe. It is unrelated to Redux Thunk, but it causes any group of actions dispatched synchronously to be debounced. This way you'd get one notification for A and B, and another one notification for C and D. That said writing code relying on this behavior would be fragile in my opinion.

like image 97
Dan Abramov Avatar answered Nov 06 '22 05:11

Dan Abramov


I'm still in the process of learning Redux; however my gut instinct says that this is could be a potential candiate for some custom middleware?

like image 39
JonnyReeves Avatar answered Nov 06 '22 05:11

JonnyReeves