Time Buy
Time Buy

Reputation: 336

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 unfortunately 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 every place const dispatch = useDispatch()

Looking for improvements :)

Upvotes: 0

Views: 33

Answers (1)

Konrad
Konrad

Reputation: 24661

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()

Upvotes: 1

Related Questions