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