Divde your actions up in different states: pending, success, error. When your request is pending your component can show a loading screen that's replaced when the request is fulfilled or errors out. With the help of redux-thunk you can create asyc actions.
In somewhat pseudo-code this would work like this:
Your actionTypes:
export const GET_EXAMPLE_ERROR = 'GET_EXAMPLE_ERROR':
export const GET_EXAMPLE_SUCCESS = 'GET_EXAMPLE_SUCCESS':
export const GET_EXAMPLE_PENDING = 'GET_EXAMPLE_PENDING':
Your actions:
export function getExampleSuccess(payload) {
return {
type: exampleActionTypes.GET_EXAMPLE_SUCCESS,
payload,
};
}
export function getExampleError(error) {
return {
type: exampleActionTypes.GET_EXAMPLE_ERROR,
error,
};
}
export function getExamplePending() {
return {
type: exampleActionTypes.GET_EXAMPLE_PENDING,
};
}
export function getExample() {
return async dispatch => {
dispatch(getExamplePending());
try {
const result = await exampleService.getData();
dispatch(getExampleSuccess(result));
} catch (error) {
dispatch(getExampleError(error));
}
};
}
Your reducer:
export default function exampleReducer(state = initialState.example, action) {
switch (action.type) {
case exampleActionTypes.GET_EXAMPLE_ERROR:
return {
...state,
example: {
...state.example,
error: action.error,
pending: false,
},
};
case exampleActionTypes.GET_EXAMPLE_SUCCESS:
return {
...state,
example: {
...state.example,
result: action.payload,
pending: false,
},
};
case exampleActionTypes.GET_EXAMPLE_PENDING:
return {
...state,
example: {
...state.example,
error: null,
pending: true,
},
};
default:
return state;
}
}
Your Component:
class ExampleComponent extends React.Component {
componentDidMount() {
this.props.getExample();
}
render() {
if( this.props.pending ) {
return <Loader />;
}
return <div>Your component</div>
}
}
const mapStateToProps => ({
pending: state.example.pending
});
const mapDispatchToProps => ({
getExample
})
export default connect(mapStateToProps, mapDispatchToProps)(ExampleComponent)
Note that this is an example of a single call. Your pending state can be a compbination of multiple pending states in different parts of your redux store.