this is the source code of redux-thunk library:
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
I can not understand how "thunk" and "thunk.withExtraArguent" are different from each other.
const thunk=createThunkMiddleware()
// this is the middleware that we use for our async requests
However thunk.withExtraArgument is the SAME createThunkMiddleware function but this time it is just being passed as a reference. We are able to pass an argument here but we cannot pass the argument to the thunk.
Can someone explain the difference please? To me thunk and thunk.withExtraArgument are same
In my universal javascript app, I created axios instance and redux store on the client and server. I pass the client-side axios instance to the client-side store and server-side axios instance to the server-side store.
Since reducers are supposed to be “pure” (they don’t change anything outside their scope) we can’t do any API calls or dispatch actions from inside a reducer. If you want an action to do something, that code needs to live inside a function. Normally our actions are just plain objects, we just dispatch them to the reducer directly. Redux-thunk is a middleware that looks at every action that passes through the system, and if it’s a function, it calls that function. Redux will pass two arguments to thunk functions: dispatch, so that they can dispatch new actions if they need to; and getState, so they can access the current state. REdux-thunk middleware gives us the ability for an action creator to return a function instead of an action object. However extraArgument is not defined with thunk function.
const thunk = createThunkMiddleware()
When I created each of redux store copies, I also created a custom instance of axios and pass that custom instance into redux thunk as an extra third argument. Then in our action creators whenever I make some type of network request, I receive the customized copy of axios rather than the actual module itself. Then I can make request without actually worry about whether we are on the client or on the server. thunk.withExtraArgument
is the middleware that extra argument is defined. So I use the thunk.withExtraArgument and pass the axios instances.
thunk
is a fancy name for a function that is used to delay a calculation until results are needed