Home > database >  React - Change button to loading status whilst fetching data
React - Change button to loading status whilst fetching data

Time:06-21

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

 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>

CodePudding user response:

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>
)
  • Related