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;
}
};
UPDATE 2021 with hooks
using useDispatch
outside of a component will cause errors.
first, import your general store
from redux and then use the dispatch method. for example:
import store from 'YOUR_DESTINATION_TO_REDUX_STORE'
function doSomething() {
// do your stuff
store.dispatch(YOUR_ACTION())
}
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')} />
);
}
const setErrors = (payload, dispatch) => {}
Modify the setErrors
function to take the additional argument dispatch
. Now you should be able to reuse the setErrors
in many components.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.