'React Looking for Functions Code Improvement
I use Redux. Every time I have to use part of the code:
const dispatch = useDispatch()
And then call the function like:
dispatch(endpointError(true))
What I want to achieve is to have some one place and then export plus call the proper function. Just keep it in one place like:
const errorFunctions = () => {
const dispatch = useDispatch()
setEndpointError = () => dispatch(endpointError(true))
}
export const { setEndpointError } = errorFunctions
And then just use only setEndpointError() when I will need it. It looks sexy I think.
For example when you would need to keep your all code shorter it is a plus like in error handling I think so.
But there it is not legal and we cannot unfortunatelly make it. Devs do you see have can we write it and make it working?
My idea is like you have 20 different screens, everywhere would be similar error handling and would be good to not write everyplace const dispatch = useDispatch()
What do you think Devs? Looking for improvements :)
Solution 1:[1]
You can create a custom hook for this:
export const useErrors = () => {
const dispatch = useDispatch()
return {
setEndpointError: () => dispatch(endpointError(true)),
setOtherError: () => dispatch(otherError())
}
}
Than you use it like this:
const { setEndpointError, setOtherError } = useErrors()
setEndpointError()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Konrad Linkowski |
