is it considered good practice to pass callBacks to redux async action?

JavascriptReactjsRedux

Javascript Problem Overview


I want to show different notification bars for success/error responses, I pass two callBacks to an redux async action in my react component like this:

<Button
  onClick={e => this.props.actions.asyncAction(item, this.showSuccessBar, this.showErrorBar)}
/>

where asyncAction looks like this:

export function asyncAction(item, successCallback, errorCallback) {
  return (dispatch, getState) => {
    dispatch(requestItem(item));
    return fetch("api.some_url/items/item")
      .then(response => response.json())
      .then(json => {
        if (json.success) {
          dispatch(receivePostsSuccess(reddit, json));
          successCallback();
        } else {
          dispatch(receivePostsFail(reddit, json));
          errorCallback();
        }
      });
    }
  };
}

Is this considered against the pattern? in other words, Should Notification Bars open according to the state change instead of callBacks?

Javascript Solutions


Solution 1 - Javascript

The pattern is fine per se. If this is a notification local to the component, feel free to avoid wiring it through Redux.

That said callbacks are completely unnecessary because you are already returning the promise. Just wait for its completion.

this.props.dispatch(asyncAction(item)).then(onSuccess, onFailure);

However if you have many components with such notification bars, it's better to have a reducer keeping the current notification and reacting to actions.

Solution 2 - Javascript

This would be bi-directional data flow, which breaks the first rule of flux.

Solution 3 - Javascript

I suggest having separated store named smth like NotificationStore and build notifications infrastructure around it. You can use callbacks, but it's way to big problems in future.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnaifenView Question on Stackoverflow
Solution 1 - JavascriptDan AbramovView Answer on Stackoverflow
Solution 2 - JavascriptBrigandView Answer on Stackoverflow
Solution 3 - JavascriptykravvView Answer on Stackoverflow