Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  7] [ 4]  / answers: 1 / hits: 7637  / 5 Years ago, tue, december 31, 2019, 12:00:00

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;
}
};

More From » reactjs

 Answers
3

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')} />
);
}

[#5205] Thursday, December 26, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
felixa

Total Points: 180
Total Questions: 113
Total Answers: 108

Location: Palau
Member since Sat, Aug 21, 2021
3 Years ago
;