25

I want to understand what is more general or correct way of error handling with React-Redux.

Suppose, I have phone number sign up component.

That Component throws an error say if the input phone number is invalid

What would be a best way to handle that error?

Idea 1: Create a component, which takes an error and dispatches an action whenever an error is passed to it

idea 2: Since the error is related to that component, pass that error to a component (which isn't connected to redux i.e the error handler component won't dispatch the action)

Question: Can someone guide me on proper-way of error handling in React-Redux for large-scale app?

1
  • 1
    How does validation of the phone number happen, synchronous or asynchronous, after the user does something or immediately? What do you want to happen, visible to the user? Redux is for storing the state of your app, it seems a bit unrelated to your question. Commented Oct 7, 2019 at 9:11

4 Answers 4

27
+50

I would say that neither of your initial ideas capture the whole picture. Idea 1 is just a callback. If you want to use a callback: useCallback. Idea 2 will work and is preferable if you don't need to use redux. Sometimes you're better off using redux. Maybe you're setting form validity by checking none of the input fields have errors or something similar. Since we're on the topic of redux, let's assume that's the case.

Usually the best approach to error handling with redux is to have an error field in state that is then passed to an error component.

const ExampleErrorComponent= () => {
  const error = useSelector(selectError);
  if (!error) return null;
  return <div className="error-message">{error}</div>;
}

The error component doesn't have to just display an error, it could also do side effects with useEffect.

How the error is set/unset depends on your application. Let's use your phone number example.

1. If the validity check is a pure function, it can be done in the reducer.

You would then set or unset the error field in response to phone number change actions. In a reducer built with a switch statement it could look like this.

case 'PHONE_NUMBER_CHANGE':
  return {
    ...state,
    phoneNumber: action.phoneNumber,
    error: isValidPhoneNumber(action.phoneNumber) ? undefined : 'Invalid phone number',
  };

2. If errors are reported by the backend, dispatch error actions.

Let's say you're sending the phone number to a backend that does validation before it does something with the number. You can't know if the data is valid on the client side. You'll just have to take the server's word for it.

const handleSubmit = useCallback(
  () => sendPhoneNumber(phoneNumber)
    .then(response => dispatch({
      type: 'PHONE_NUMBER_SUBMISSION_SUCCESS',
      response,
    }))
    .catch(error => dispatch({
      type: 'PHONE_NUMBER_SUBMISSION_FAILURE',
      error,
    })),
  [dispatch, phoneNumber],
);

The reducer should then come up with an appropriate message for the error and set it.

Don't forget to unset the error. You can unset the error on a change action or when making another request depending on the application.

The two approaches I outlined are not mutually exclusive. You can use the first to display locally detectable errors and also use the second to display server side or network errors.

3
  • 1
    I so appreciate your response and this definitely looks a better approach compared to what I do. I am still looking for some more suggestions and hence I have started a bounty on this question.
    – Alwaysblue
    Commented Oct 9, 2019 at 11:17
  • 1
    what happens when user changes route and come back to the same route, the error will be still there being displayed because it is saved in the reducer.
    – Klaffy
    Commented Jun 17, 2021 at 14:31
  • 1
    If you need to report errors to some tracker, though, the 2nd solution is going to get very cumbersome to write, no? You're going to end up lots of imperative logic like Sentry.setContext in every thunk. is there a better centralized, declarative way of doing this? Commented Aug 22, 2022 at 10:18
1

I would use a formik with yup validation. then, for server-side error i would use something like this:

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Spinner } from "@blueprintjs/core";

export default ({ action, selector, component, errorComponent }) => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(action());
  }, [dispatch, action]);

  const DispatchFetch = () => {
    const { data, isRequesting, error } = useSelector(selector());
    if (!isRequesting && data) {
      const Comp = component;
      return <Comp data={data}></Comp>;
    } else if (error) {
      if (errorComponent) {
        const ErrorComp = errorComponent;
        return <ErrorComp error={error}></ErrorComp>;
      }
      return <div>{error}</div>;
    }
    return <Spinner></Spinner>;
  };

  return <DispatchFetch></DispatchFetch>;
};
1
  • Looks interesting anerco, Thanks for answering :)
    – Alwaysblue
    Commented Oct 15, 2019 at 22:19
1

It depends on what kind of error handling are you talking about. If it's only form validation handling then I don't think you need Redux for that - please read this article. If your error is only going to be "consumed" within that component, why send it to redux? You can easily use your local state for that.

On the other hand, if you want to show some kind of error notification to user indicating whether any HTTP call on site failed, you could benefit with redux by dispatching error from all parts of your application (or even generically your middleware)

dispatch({ type: 'SET_ERROR_MESSAGE', error: yourErrorOrMessage });

// simple error message reducer
function errorMessage(state = null, action) {
  const { type, error } = action;

  switch (type) {
      case 'RESET_ERROR_MESSAGE':
          return null;
      case 'SET_ERROR_MESSAGE':
          return error;
  }

  return state
}

You need to define how is your state going to be organized and whether you need to put some state in redux or just keep it in local state of your component. You could put everything in redux, but personally I'd say it's an overkill - why would you put state X in component Y if only component Y cares about that state? If you structure your code correctly you shouldn't have problem with moving that state from local to redux later on, if for some reason other parts of your app start to depend on that state.

1

I think about it like this, what should be state? And what should be derived from state? State should be stored in redux, and derivations should be calculated.

A phone number is state, which field has focus is state, but whether or not it's valid, that can be derived from the values in state.

I would use Reselect to cache derivations and return the same results when the relevant state hasn't been modified.

export const showInvalidPhoneNumberMessage = createSelector(
  getPhoneValue,
  getFocusedField,
  (val, focus) => focus !== 'phone' && val.length < 10 // add other validations.
)

You can then use the selector in mapStateToProps in all components that may care about this value, and you can use it in async actions as well. If the focus hasn't changed, or the value of the field hasn't changed, then no recalculation will occur, it'll return the previous value instead.

I'm adding the selected state check just to show how multiple pieces of state can come together to result in one derivation.

I personally try to approach things by keeping my state as small as possible. For instance, let's say you wanted to create your own calendar. Will you store every single day in state, or do you just need to know a couple things like the current year and month currently being viewed. With just these 2 pieces of state you can calculate the days to display on a calendar, and don't need to recalculate until one of them changes, and this recalculation will happen virtually automatically, no need to think about all the ways theat they could change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.