[Part 2] How to use redux thunk

sirimainsorn

Sirima Insorn

Posted on January 21, 2022

[Part 2] How to use redux thunk

We need to example is loading component.
First, fixed constant in ./global/global.constant.js file (example):

export const globalConstant = {
  SPINNER_LOADING: "SPINNER_LOADING",
};
Enter fullscreen mode Exit fullscreen mode

Next, We need to create an ./global/global.action.js file, Redux Thunk allows you to write action creators that return a function instead of an action.:

export const globalAction = {
  spinnerLoading(isOpen) {
    return {
      type: "SPINNER_LOADING",
      isOpen,
    };
  },
};
Enter fullscreen mode Exit fullscreen mode

And create an ./global/global.reducer.js that take these actions and return a new state:

import { globalConstant } from "./global.constant";

export const GlobalReducer = (state = { loading: false }, action) => {
  switch (action.type) {
    case globalConstant.SPINNER_LOADING:
      return {
        ...state,
        loading: action.isOpen,
      };

    default:
      return state;
  }
};
Enter fullscreen mode Exit fullscreen mode

How to use dispatch and selector

Import GlobalAction from ./store/global/global.action to ./App.js

import { GlobalAction } from "./store/global/global.action";
Enter fullscreen mode Exit fullscreen mode

and call state from reducer:

const { loading } = useSelector((state) => state.globalReducer);
Enter fullscreen mode Exit fullscreen mode

Now, handle event to show loading:

<button
   className="..."
   onClick={() => {
      dispatch(GlobalAction.spinnerLoading(true));
   }}
>
  Click Loading
</button>
Enter fullscreen mode Exit fullscreen mode

Next, run appilcation:

yarn start
Enter fullscreen mode Exit fullscreen mode

Result:

Image description

You can view a demo of the website we’re creating here

💖 💪 🙅 🚩
sirimainsorn
Sirima Insorn

Posted on January 21, 2022

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

Sign up to receive the latest update from our blog.

Related

[Part 2] How to use redux thunk
react [Part 2] How to use redux thunk

January 21, 2022