Answer a question

I have a functional component as follows and i have a function which has two dispatches. One sets the error message and the other removes the error message after a brief time out period. The functionality of setting errors and clearing comes in many other components therefore I want to have the two dispatch functions in another file to allow code reusability. I am unable to do this as i get an error which says i can only use useDispatch inside a functional component. How do i overcome this ?

The component

const Checkout = () => {
  const dispatch = useDispatch();

  const setErrors = (payload) => {
   dispatch({
     type: 'SET_ERRORS',
     payload,
   });

  setTimeout(() => {
    dispatch({
     type: 'CLEAR_ERRORS',
    });
  }, 2500);
 };

 return (
  <>
 // JSX stuff come here
  <>
 )
}

The reducer

const initialState = {
  message: null,
  status: false,
};

export default (state = initialState, action) => {
  switch (action.type) {
    case 'SET_ERRORS':
      return {
        ...state,
        message: action.payload,
        status: true,

      };
    case 'CLEAR_ERRORS':
      return {
        ...state,
        message: null,
        status: false,

      };
    default:
      return state;
  }
};

Answers

You can create your own custom hook called for example useErrorDispatcher and use it in many functional components. Also please note that hooks are only allowed within functional components.

export const useErrorDispatcher = () => {
    const dispatch = useDispatch();

    return (payload) => {
        dispatch({ type: 'SET_ERRORS', payload});
        setTimeout(() => dispatch({type: 'CLEAR_ERRORS'}), 2500);
    }
}

Usage:

const MyComponent = (props) => {
    const errorDispatcher = useErrorDispatcher();

    return (
        <button onClick={() => errorDispatcher('an error occurred')} />
    );
}
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐