Why Redux-thunk?

jaebungs

Jae Park

Posted on February 5, 2021

Why Redux-thunk?

Note: I am writing this to organize my thought and keep some records. Please let me know if something is wrong or have a better explanation. Thank you!


If you are app does not interact with a server or use API call, you wouldn't need redux-thunk because you don't need async actions.
Problems come when any server-side(REST API) is involved.


Why problems?

Redux store only supports synchronous. See Redux documentation below.
By itself, a Redux store doesn't know anything about async logic. It only knows how to synchronously dispatch actions, update the state... ([https://redux.js.org/tutorials/fundamentals/part-6-async-logic])


Can I use API call in a reducer?

No. Reducer is a pure function. It should not cause side effects and it should not directly mutate the state. Anyway, mutating state is an ah oh… in React. 
Redux uses action and reducer to update your app's state. By using these two, people can easily tell how data flow and when your state is changing.
Reducer should copy the state first, then overwrite the value you want to change in the state.

return {
  ...state,
  zip: M0R0O0
}
Enter fullscreen mode Exit fullscreen mode

The solution is here!

Simply saying Redux-thunk is a middleware that allows users to use asynchronous functions when API calls are necessary.
As the document said dispatching action happens immediately, but redux-thunk can make a delay or apply a condition.

'Action' is an object, so 'action creator' should return the action object. Redux-thunk allows an action creator to return a function! Now we can do any asynchronous work.

Let's see how thunk works in code.

export const addToMyBar = (cocktail, id) => async (dispatch) => {
    await fetch('http://localhost:5000/', {
    })
    .then((res)=>res.json())
    .then((data)=> {
        dispatch({type: 'ADD_TO_MY_BAR', data});
    })
    .catch(err => console.log(err))
}
Enter fullscreen mode Exit fullscreen mode

How to use?

Install the package

npm install --save redux-thunk
Enter fullscreen mode Exit fullscreen mode

Import.

import { createStore, combineReducers, applyMiddleware, compose  } from "redux";
import thunk from 'redux-thunk';

Enter fullscreen mode Exit fullscreen mode

Example )

export default () => {
  const store = createStore(
    combineReducers({
      cocktails: cocktailsReducers,
      myBar: myBarReducer,
    }),
    compose(
      applyMiddleware(thunk),
      window.__REDUX_DEVTOOLS_EXTENSION__ && 
      window.__REDUX_DEVTOOLS_EXTENSION__()
    )
  );
  return store;
};
Enter fullscreen mode Exit fullscreen mode

Thank you.
I know this is not well unorganized...

💖 💪 🙅 🚩
jaebungs
Jae Park

Posted on February 5, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related