I am a bit confused when it comes to dispatching actions. In the actions sometimes I see this:
export const getConfig = () => dispatch => {
const res = await axios.get('/api/users');
dispatch({
type : TYPES.GET_CONFIG,
payload : res.data
});
}
and sometimes I see:
export const getConfig = () => {
const res = await axios.get('/api/users');
return{
type : TYPES.GET_CONFIG,
payload : res.data
};
}
Are they both same? or they have their own use cases? When to use what?
Thanks.
By default actions in Redux are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects.
Ex:
return{
type : TYPES.GET_CONFIG,
payload : res.data
};
Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store's dispatch method, which is then used to dispatch regular synchronous actions inside the body of the function once the asynchronous operations have completed.
Ex:
dispatch({
type : TYPES.GET_CONFIG,
payload : res.data
});
thunk is a concept in programming where a function is used to delay the evaluation/calculation of an operation.
Explanation Reference
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