We need to example is loading component.
First, fixed constant in ./global/global.constant.js
file (example):
export const globalConstant = {
SPINNER_LOADING: "SPINNER_LOADING",
};
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,
};
},
};
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;
}
};
How to use dispatch and selector
Import GlobalAction
from ./store/global/global.action
to ./App.js
import { GlobalAction } from "./store/global/global.action";
and call state
from reducer
:
const { loading } = useSelector((state) => state.globalReducer);
Now, handle event to show loading:
<button
className="..."
onClick={() => {
dispatch(GlobalAction.spinnerLoading(true));
}}
>
Click Loading
</button>
Next, run appilcation:
yarn start
Result:
You can view a demo of the website we’re creating here
Top comments (0)