Create a loading(spinner) in an asynchronous request with React

Asked

Viewed 921 times

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.

1 answer

1


Following the comment made by Vinicius: You create the loading state, and start it with false. Immediately before making the call in the API, you change the state to TRUE, and when the request is finished, you set it back to false.

You must create the state at the beginning of your component, something like that:

const [loading, setLoading] = useState(false);

Remember to import useState. In your Handle function, it should look something like this (with setLoading(true) before calling the api:

import spinnerImg from '../../assets/spinner.svg';


async function handleLogin(e){
    e.preventDefault();

    if(validation){
        setValidationId('Invalido');
        return;
    }else{
        setValidationId('');

        try {
            setLoading(true);
            const response = await api.post('session', { id });
            localStorage.setItem('ongId', id);
            localStorage.setItem('ongName', response.data.name);

            setLoading(false);
            history.push('/profile');

        } catch (err) {
            console.log(err);
            alert('Falha no login');
        }
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.