Hey, I'm struggling to explain this but let me try to make it clear:
LoginDispatch.ts
const useLoginDispatch = () => {
const dispatch = useDispatch()
const setLoginScreen = (screen: LoginScreen) => {
dispatch(loginActions.setLoginScreen(screen))
}
const setRegisterError = (message: string) => {
dispatch(loginActions.setRegisterError(message))
}
// It feels like a lot of repetitive code writing dispatch() for each action. Is there a way to automate this process?
// Take note that the exports below match the names in loginActions
return { setLoginScreen , setRegisterError }
}
All I'm doing is using dispatch()
with every function exported from loginActions
. To change the login screen, I simply type:
LoginComponent.tsx
const loginDispatch = useLoginDispatch()
loginDispatch.setLoginScreen(LoginScreen.Register)
Instead of:
LoginComponent.tsx
const dispatch = useDispatch()
dispatch(loginActions.setRegisterError(message))
I could manually continue adding functions to LoginDispatch.ts, but with so many actions in my app, is there a way to automatically map dispatch
to all of the exports in LoginActions.ts and export them with their original function names?
If you want to take a look, here's my Actions.ts file. (Every export follows the same structure, except for parameters and return types)
Actions.ts
export const setLoginScreen = (screen: LoginScreen): LoginActionTypes => ({
type: LoginActions.SET_LOGIN_SCREEN,
payload: screen
})
export const setRegisterError = (message: string): LoginActionTypes => ({
type: LoginActions.SET_REGISTER_ERROR,
payload: message
})
NOTE: I am leaving Actions.ts unchanged because other functions (like put() in sagas) also rely on these functions.