Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React – Change button to loading status whilst fetching data

I have tried a few variations of this, but can’t seem to get it working. I have a custom hook that posts data once the user clicks a button after having chosen a value from a dropdown.

I want the button to be disabled until the fetch request returns a status of 200. Essentially I want the user to not continue to the next page until the request has completed. Here is some code:

customHook

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 const postData = () => {
        setLoading(true);
        axios({
            url: -
            headers: -,
            method: -,
            data: -,
            responseType: -
        })
            .then((response) => {
                    setLoading(false);
                }
            })
            .catch((error) => {
                setLoading(false);
                setError(error.response.data));
            });
    };

Button Component

                <Button
                    onClick={onClickHandler}
                    loading={SOME STATE HERE TO ACHIEVE THIS}
                >
                    {Continue}
                </Button>

>Solution :

You could simply use a boolean state variable.

const [loading, setLoading] = useState(false)

const onClickHandler = () => {
  setLoading(true)
  performNetworkCall()
    .finally(() => {
      setLoading(false)
    }
}

return (
  <Button onClick={onClickHandler} loading={loading} >
    {Continue}
  </Button>
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading