how to show loader in react . using hooks
10,110
Solution 1
Add empty array to sencod parameter to useEffect
.
It works like componentDidMount()
in functional component.
const { useState, useEffect } = React;
const Counter = () => {
const [count, setCount] = useState(0)
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
setTimeout(() => {
setIsLoaded(true);
}, 3000);
}, []); // here
return (
<div>
{
isLoaded &&
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
}
</div>
)
}
ReactDOM.render(<Counter />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0-alpha.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0-alpha.2/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Solution 2
i usualy use this code to show loading when request data is processing and hide when it's done
const Loader = () => {
const {data, setdata} = useState([])
useEffect(()=>{
axios.get('your host').then(res => {
setdata(res.data);
}).catch(err => {
setdata(res.data);
}
});
return (
<div>
{data.length > 0
?
<div style={{position:"fixed",display:"flex",justifyContent:"center",alignItems:"center",width:'100%',height:'100%',zIndex:999999}}> </div>
:
<Spin tip="Loading..." style= {{zIndex:999999}}>
</Spin>
</div>
);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Author by
user944513
Updated on June 08, 2022Comments
-
user944513 almost 2 years
I am using
axios
forcommunicate
with server.I want to show loader when user request to server and hide the loader when request is completeSo i make a custom component to do this task .but my UI hang when I click multiple times on same button
const Loader = () => { const { loadingCount } = useLoadingState(), {showLoading, hideLoading} = useLoadingActions(); useEffect(()=>{ const self = this axios.interceptors.request.use(function (config) { showLoading(); return config }, function (error) { return Promise.reject(error); }); axios.interceptors.response.use(function (response) { // spinning hide // self.props.loading(false) hideLoading() return response; }, function (error) { hideLoading(); return Promise.reject(error); }); }) return ( <div> {loadingCount > 0 ?<div style={{position:"fixed",display:"flex",justifyContent:"center",alignItems:"center",width:'100%',height:'100%',zIndex:999999}}> {/*{loadingCount > 0 ? */} <Spin tip="Loading..." style={{zIndex:999999}}></Spin> {/*: null}*/} </div>: null} </div> ); };
Problem is on
useeffect
when I comment out useEffect code it works perfectly .
NoTe : showloading and hideloading increase and decrease the loading count.
I think I have deallocate axios object the when component is unmount.???