I would like to add a Loader component to be rendered whenever an API call is being made in React. I want to use react context + hooks instead of redux.
As the rules of react hooks say, we should not use react hooks outside the react component. But I need to dispatch the SHOW_LOADER
and HIDE_LOADER
inside the Axios interceptor as below.
Is there a way to achieve this?
import axios from "axios";
axios.interceptors.request.use(
config => {
dispatch({
type: "SHOW_LOADER"
})
return config;
},
error => {
dispatch({
type: "HIDE_LOADER"
})
return Promise.reject(error);
}
);
axios.interceptors.response.use(
response => {
dispatch({
type: "HIDE_LOADER"
})
return response;
},
error => {
dispatch({
type: "HIDE_LOADER"
})
return Promise.reject(error);
}
);
function GlobalLoader(){
const [state,dispatch] = useContext(LoaderContext);
return(
<div>
{
state.loadStatus &&
<Loader
type = "Puff"
color = "#00BFFF"
height = {100}
width = {100}
timeout = {3000} />
}
</div>
);
}
export default GlobalLoader;
Please let me know if more information is required.:)
useEffect
inGlobalLoader
? – IquiqueuseEffect
will not be executed when we make an API request in the child component. – IncomeruseEffect
does not need to execute, you are passing a function to interceptor, that will execute – Iquiqueaxios.interceptor
was not detecting the API request made in the child components. – Incomer