Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...