How to make a single loader reducer for whole application, React

1.5k Views Asked by At

I have an application in which I have multiple components as well as actions and reducers for each component. I am using redux-pack for promise handling as well.

So here is the situation, I just want to use a single reducer for my whole application which handles my page-loader. That means, whenever an API call start, the loader should show and it should hide when the API ends. I don't want to write a separate action for this.

Please help me with your suggestions. Thanks in advance.

1

There are 1 best solutions below

1
On

, I don't have the proper idea redux-pack but I have achieved this using react-redux. There is library react-loading-overlay library you can use it or create a new loading-overlay own.

https://github.com/derrickpelletier/react-loading-overlay Link of the library if you want.

Now coming to the code:-

I have created a global state in redux named as loadingState

//this is my action.
export const ENABLE_OR_DISABLE_LOADING = 'ENABLE_OR_DISABLE_LOADING';

export function enableOrDisableLoading (value = true, msg='Loading your content') {
    return {
        type: ENABLE_OR_DISABLE_LOADING,
        payload: {isLoading: value, msg: msg}
    };
}

//this is my reducer.
export function loading(state={isLoading: false, msg: 'Please wait...'}, action) {
    switch (action.type) {
        case ENABLE_OR_DISABLE_LOADING:
            return action.payload;
        default:
            return state;
    }
}

Add this reducer to your store.


My HOC is like this.

import LoadingOverlayWrapper from 'react-loading-overlay';


class AdminImpl extends React.Component {
  return (
            <LoadingOverlayWrapper
                active={this.props.isLoading}
                spinner
                zIndex={1000}
                className="height100"
                text={this.props.msg}
            >
             <SideBar/>
             {this.props.child}
            </LoadingOverlayWrapper>
        );
}

const mapStateToProps = (state) => {
    return state.loading;
};

export const Admin = connect(mapStateToProps)(AdminImpl);



Now dispatch action from anywhere from your app.

//start Loading state
store.dispatch(enableOrDisableLoading(true, 'Your loading msg'));

//start Loading state
store.dispatch(enableOrDisableLoading(false));