Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I use custom error actions to handle both API errors and user input errors


Can I use custom error actions to handle both API errors and user input errors


To handle both API errors and user input errors in Redux, you can create custom error actions that are dispatched when an error occurs. Here is an example of how you can do this:

javascript
// actions.js
import { createAction } from '@reduxjs/toolkit';

const errorAction = createAction('ERROR');

export const setError = (error) => errorAction(error);

// reducers.js
import { createReducer } from '@reduxjs/toolkit';
import { setError } from './actions';

const initialState = {
  error: null,
};

const errorReducer = createReducer(initialState, {
  [setError.type]: (state, action) => {
    state.error = action.payload;
  },
});

export default errorReducer;

// components.js
import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { setError } from './actions';

const MyComponent = () => {
  const dispatch = useDispatch();
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then((response) => response.json())
      .then((data) => setData(data))
          .catch((error) => dispatch(setError(error)));
  }, []);

  return (
    <div>
      {data ? (
        <p>Data: {data}</p>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};

export default MyComponent;

In this example, we create an `setError` action creator that dispatches the `ERROR` action with the error message. In the reducer, we handle this action by updating the state with the error message.

To handle user input errors, you can create a separate action creator for that. For example:

javascript
// actions.js
import { createAction } from '@reduxjs/toolkit';

const errorAction = createAction('ERROR');

export const setError = (error) => errorAction(error);

export const validateInput = (input) => {
  if (!input) {
    return setError('Input is required');
  }
  return setError(null);
};

Then, in your component, you can use this action creator to handle user input errors:

javascript
// components.js
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { validateInput } from './actions';

const MyComponent = () => {
  const dispatch = useDispatch();
  const [input, setInput] = useState('');

  const handleInputChange = (event) => {
    const value = event.target.value;
    setInput(value);
    dispatch(validateInput(value));
  };

  return (
    <div>
      <input type="text" value={input} onChange={handleInputChange} />
      {input && <p>Input: {input}</p>}
    </div>
  );
};

export default MyComponent;

In this example, we create a `validateInput` action creator that checks if the input is valid. If it's not, it dispatches the `ERROR` action with an error message. In the component, we use this action creator to handle user input errors.

By using custom error actions, you can handle both API errors and user input errors in a centralized and robust manner.

Citations:
[1] https://www.pluralsight.com/resources/blog/guides/centralized-error-handing-with-react-and-redux
[2] https://www.geeksforgeeks.org/how-to-handle-errors-in-react-redux-applications/
[3] https://firehydrant.com/blog/graceful-error-handling-with-redux/
[4] https://stackoverflow.com/questions/58266418/correct-way-of-error-handling-in-react-redux
[5] https://alexandrempsantos.com/sane-error-handling-react-redux/