Manoj Rawat
Manoj Rawat

Reputation: 312

How redux-thunk works?

So I am currently new with redux and stuck in the middleware part. I need to know how these two codes interact with each other.

My action creator:

import jsonPlaceHolder from '../APis/jsonPlaceHolder';

export const fetchPosts= ()=>{

  return async (dispatch)=>{

      const response = await jsonPlaceHolder.get('/posts');

      dispatch({type:'FETCH_POSTS',payload: response});

  };

};

redux-thunk code:

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;

Upvotes: 1

Views: 907

Answers (1)

Kaca992
Kaca992

Reputation: 2267

Plain redux only works with sync actions. Redux thunk gives you the ability to work with async actions (to dispatch multiple actions from a single action creator, for async actions that is usually the REQUEST/RESPONSE/ERROR action). Middleware is something that stands between you dispatching the action and reducer updating the store. Since redux only works with plain objects, to use a action creator (like fetchPosts) you need something (redux-thunk here). It simply injects the dispatch parameter (and getState that gives you the ability to get the current state if your action creator depends on it).

The next(action) inside middleware is the method that propagates your action object to the next middleware(or if it is the last one to your reducer). Redux-thunk checks if the thing you dispatched is a function(since we said that redux can only work with plain objects), and if it is a function it just injects the above mentioned parameters.

So it is basically:

dispatch(fetchPosts()) -> redux-thunk-middleware -> it is function so lt's call it with injected dispatch/getState (this will not be propagated to the reducer) -> dispatch({type:'FETCH_POSTS',payload: response}) -> redux-thunk-middleware -> not a function, let it through -> reducer -> update state

Hope this helps.

Upvotes: 3

Related Questions