I am trying to understand the code that my past colleague has written.
From what I understand, useDispatch takes in an object that contains the action type and payload, which will be compared to all the reducers and the state will be changed accordingly. However, in the below code, he passes an entire function instead of an object. My question is why can useDispatch still function without passing in an object, as the function does not return anything.
Below is the useDispatch function and the action function.
const dispatch = useDispatch();
const handleSubmit = (e: any): void => {
dispatch(login("email", "password"));
};
export const login =
(email: string, password: string) =>
async (dispatch: Dispatch<LoginActions>) => {
try {
// Update the store
dispatch({
type: USER_ACTIONS.USER_LOGIN_REQUEST,
});
const data = await loginRequest({ email, password });
dispatch({
type: USER_ACTIONS.USER_LOGIN_SUCCESS,
payload: data,
});
} catch (error: any) {
dispatch({
type: USER_ACTIONS.USER_LOGIN_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
For redux itself, you can only dispatch action which is a plain JS object(or an action creator returns an action, this action is a plain JS object must have a type field.). But with various middlewares, you can dispatch various things such as a thunk, plain JS object action, etc. The middleware will transform the action to plain JS object action in the end.
When using the redux-thunk middleware, you can dispatch a thunk like this:
const thunkFunction = (dispatch, getState) => {
// logic here that can dispatch actions or read state
}
store.dispatch(thunkFunction)
The login thunk action creator does return a thunk.
A thunk action creator is a function that may have some arguments, and returns a new thunk function. See Writing Thunks
Another example, redux-promise-middleware,
Given a single action with an async payload, the middleware transforms the action to separate pending action and a separate fulfilled/rejected action, representing the states of the async action.
You can dispatch an action with async payload:
const response = dispatch({
type: 'FIRST',
payload: new Promise(...),
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With