how can I create a loading circle, for example, when I make an XmlHtpp request with Axios in my view with ReactJS?
<Get/>
Currently I achieve that with the dependency tag react-axios
.
Note : react-axios is not axios. React Axios has COMPONENTS with Get, Put, etc. tags. More information: react-axios - npm
With the component <Get/>
I achieve something that I really like and that is that I can put a Progress Loading , look at the following:
render() {
return (
<div>
<Get url="/api/user" params={{id: "12345"}}>
{(error, response, isLoading, makeRequest, axios) => {
if(error) {
return (<div>Something bad happened: {error.message} <button onClick={() => makeRequest({ params: { reload: true } })}>Retry</button></div>)
}
else if(isLoading) {
return (<div>Loading...</div>)
}
else if(response !== null) {
return (<div>{response.data.message} <button onClick={() => makeRequest({ params: { refresh: true } })}>Refresh</button></div>)
}
return (<div>Default message before request is made.</div>)
}}
</Get>
</div>
)
}
In the condition if(isLoading)
I can perfectly fit an animation component, for example the <CircularProgress/>
MaterialUI one . This works great... But the logic I need doesn't allow me to use the tag for requests with react-axios <Get/>
.
For that reason, I would like to know how or where to put a "Loading" during a request with Axios... For example, if I had this:
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
Where do I put my <div>Loading...</div>
while waiting for the response or where do I manipulate a boolean variable to trigger it on render? That the variable remains false while I wait for the response and changes to true when it receives a response and there I stop the view that it is loading...
You can use
this.setState
to manipulate the state of the component when it is waiting for the request and when it finishesuse finally to make loading disappear whether the request succeeds or fails