How to coordinate server error messages between Flux and React?

旧时模样 提交于 2019-12-03 02:39:23
Dan Abramov

Since you marked the question with Redux tag, I'm assuming you use Redux.
If so, this real-world example shows error handling.

There's a reducer that reacts to any action with error field:

// Updates error message to notify about the failed fetches.
function errorMessage(state = null, action) {
  const { type, error } = action;

  if (type === ActionTypes.RESET_ERROR_MESSAGE) {
    return null;
  } else if (error) {
    return action.error;
  }

  return state;
}

The custom API middleware puts any error message into error field on the action:

  return callApi(endpoint, schema).then(
    response => next(actionWith({
      response,
      type: successType
    })),
    error => next(actionWith({
      type: failureType,
      error: error.message || 'Something bad happened'
    }))
  );

Finally, the component reads the error message from Redux store:

function mapStateToProps(state) {
  return {
    errorMessage: state.errorMessage
  };
}

As you can see, this is not any different from how you'd handle displaying fetched data.

Your idea of keeping error info in a store is fine (probably an ErrorStore). But the store doesn't need to know the component interested in a particular error. Instead, the ErrorStore needs to emit a CHANGE event. When emitting that event, you can add an additional argument, namely the error type (which the store presumably gets from the action creator).

Now, any component can listen to the ErrorStore and check the error type (which it will get as an argument). Components can then know what kind of error was generated and decide whether they are interested in that or not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!