I have a button(Material-UI) in my ReactJs application. Now, the scenario is when a user clicks(too many times thou!) and call an API to insert my form data there are multiple clicks triggering which tends to insert twice, thrice or n times(depends on user clicks). So, I basically want a proper way to accept a single click(despite of user clicking a button n times). Can anyone suggest me a proper way of doing it.
Note: I have tried out disabling and enbaling of button on click, as well as setTimeout to call API only on single click, but it does not work. Still on production I am having issues.
So I want a proper way for implementing single click on button (let user click multiple times the button)
CodePudding user response:
Set a state variable on button click and disable the button based on the variable. So that the user will not be able to click again. And also, you can enable the button on API response.
example:
[disableButton, setDisableButton] = useState(false);
const submitFunction = () => {
setDisableButton(true);
apiCall().then(resp => {
setDisableButton(false) // enable button on api success response
// code on success response
})
.catch((error) => {
setDisableButton(false)
});
}
<button onClick={() => submitFunction()} disabled={disableButton}>Submit</button>
CodePudding user response:
One approach to solving this problem would be to use a debounce function to delay the API call until a certain amount of time has passed since the last button click. This will ensure that only one API call is made, even if the button is clicked multiple times in a short period of time.
Here's an example of how you could implement this in your React component:
`
import { useState, useCallback } from 'react';
import { debounce } from 'lodash';
function MyComponent() {
const [isLoading, setIsLoading] = useState(false);
const handleClick = useCallback(() => {
setIsLoading(true);
// debounced function that will only call the API if there hasn't been
// a button click in the last 500ms
const debouncedInsertData = debounce(insertData, 500);
debouncedInsertData();
}, []);
async function insertData() {
try {
// call API here
// ...
setIsLoading(false);
} catch (err) {
// handle error
setIsLoading(false);
}
}
return (
<button onClick={handleClick} disabled={isLoading}>
Submit
</button>
);
}
`