I'm working on a React application where I have a table of checkboxes, and the initial values of these checkboxes are fetched from an API. The challenge I'm currently facing is how to immediately update the UI in response to a user's interaction with the checkbox before the API response arrives, and then reconcile the UI state with the API response after it's received.
Here is the brief usecase
- Initially, Checkbox having api boolean value
- When a user toggle the checkboxes, the api response takes a little time to update
- So,my objective is to assign the checkbox a temporary boolean value(baesed on toggle value) for about 10 second
- Then assign the checkbox value from the API after 10 second
Here's the relevant part of my code:
// Function to handle checkbox click and update control
const handleCheckboxClick = async (controlId, property, value, setLocalState) => {
// Create the patchData object with the updated value
const updatedValue = !value;
const patchData = {
[property]: updatedValue,
};
try {
// Send the PATCH request to update the control
setUpdateLoading(true);
await http.patch(
`${baseURL}/threat-catalog/control-analysis/${controlId}`,
patchData
);
// Trigger an immediate refetch of the data
queryClient.invalidateQueries([
'apiData',
`${baseURL}/threat-catalog/control-analysis?businessProcessId=${processId}`,
]);
// Temporarily update the local state with the opposite value
// This will make the checkbox appear to change for 10 seconds
setLocalState((prevState) => ({
...prevState,
[property]: !value,
}));
// After 10 seconds, revert the local state to the API value
setTimeout(() => {
setLocalState((prevState) => ({
...prevState,
[property]: value,
}));
}, 10000); // 10 seconds delay (10000 milliseconds)
} catch (err) {
console.error('Error:', err);
// Handle error
}
};
In my JSX code, I'm calling handleCheckboxClick as follows:
<input
id={`applicable-checkbox-${controls.id}`}
type="checkbox"
defaultChecked={controls?.is_applicable}
checked={localState[controls.id]?.is_applicable || false}
onClick={() => handleCheckboxClick(controls.id, 'is_applicable',
localState[controls.id]?.is_applicable)}
/>
Aucun commentaire:
Enregistrer un commentaire