I'm currently attempting to create a custom hook, as in my app I re-use the same function a lot of times at the moment in a few different places, and it's not sustainable.
The function is meant to call useDispatch() upon completion of an action, and it then updates state with a given payload.
However, when I try to move it into a custom hook, it throws an error saying the following:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
This is the hook in question - it's located in a useDispatchStatus.ts and is exported as a default:
const useDispatchStatus = (payloadMessage, payloadType) => {
const dispatch = useAppDispatch()
dispatch(displayStatus({
payloadMessage: payloadMessage,
payloadType: payloadType
}))
setTimeout(() => dispatch(hideStatus()), 5000)
}
export default useDispatchStatus
This 'hook' is then called inside of a function, located inside a component, like so:
const eventHandlerFunction = () => {
try {
// some example code in here
} catch (error) {
useDispatchStatus(error, "error")
}
}
The hook itself is using a typical useDispatch(), but is a custom type since it's a TypeScript app, as defined in the RTK docs.
Does anyone know what I'm doing wrong here?
eventHandlerFunction
is not a React component, so you cannot call your hook from there. Hooks can only be called at the top level of a function component, or from another hook. To fix the error you need to move your hook out of the eventHandlerFunction
function.
To fix this, try returning the dispatch function from the hook and calling that inside of the event handler:
const useDispatchStatus = () => {
const dispatch = useAppDispatch();
const dispatchStatusDisplay = (payloadMessage, payloadType) => {
dispatch(
displayStatus({
payloadMessage: payloadMessage,
payloadType: payloadType,
})
);
setTimeout(() => dispatch(hideStatus()), 5000);
};
return dispatchStatusDisplay;
};
// Inside the component
const dispatchStatusDisplay = useDispatchStatus()
const eventHandlerFunction = () => {
try {
// some example code in here
} catch (error) {
dispatchStatusDisplay(error, "error")
}
}
The general idea is to export some function from the hook that can be called when needed.