Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 342
naifen Avatar asked Oct 15 '15 00:10

naifen


People also ask

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.

What are typical middleware choices for handling asynchronous calls in Redux?

There are two very popular middleware libraries that allow for side effects and asynchronous actions: Redux Thunk and Redux Saga. In this post, you will explore Redux Thunk.

Is Redux dispatch asynchronous?

AFAIK, dispatching action is synchronous. In case if you are willing to address the asynchronous call, you can use the thunk-middleware in redux, where dispatch is provided as a callback function which you can invoke as per your convenience.

What all packages help in making the Redux operations asynchronous?

The two to keep in mind are axios to make async requests and redux-thunk to manage async state.


1 Answers

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.

like image 112
Dan Abramov Avatar answered Sep 23 '22 20:09

Dan Abramov