DEV Community

Sirima Insorn
Sirima Insorn

Posted on

3 1

[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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more