0
I have an application with the front in React and the back with Node, and I needed that the moment the user pressed the button, the loading appeared and then the request was performed, or while the loading was loading, the request was carried out. I made a few attempts but it didn’t work out so well.
import spinnerImg from '../../assets/spinner.svg';
async function handleLogin(e){
e.preventDefault();
if(validation){
setValidationId('Invalido');
return;
}else{
setValidationId('');
try {
const response = await api.post('session', { id });
localStorage.setItem('ongId', id);
localStorage.setItem('ongName', response.data.name);
await timeOutSpinner();
history.push('/profile');
} catch (err) {
console.log(err);
alert('Falha no login');
}
}
}
function timeOutSpinner(){
setLoading(true);
setTimeout(() => {
setLoading(false);
}, 8000);
}
// Este trecho de codigo abaixo esta dentro do html, é com ele que eu chamo o loading.
{loading ? <img src={spinnerImg} alt="Loading" style={{ width: 250 }}></img> : false}
You can create a state called loading that’s how the asynchronous method of yours is called to make the API call, you change the state of the loading to true before calling the method with the await and after the await you can change the state of loading to talk. You just need to be careful because exceptions may occur during the request, so treat the state loading in these cases as well.
– Vinicius Castro