recently I have stumbled upon a dilemma on how to properly approach UI updates. The stack I am using at work is React + axios. Let’s say there is a user profile object held in the local state and the user wants to update his first name. Which way is better? Please let me know what I am missing here?
const handleUpdateUserProfile = async (newUserName) => {
const originalUserName = userProfile.name;
// Optimistically update the UI
setUserProfile(prev => ({ ...prev, name: newUserName }));
// Try to send the database request
try {
await axios.post("/some-endpoint", {...userProfile, name: newUserName });
} catch (error) {
// In case of an error go back to the previous value
setUserProfile(prev => ({...prev, name: originalUserName}));
console.error(error);
}
}
OR
const handleUpdateUserProfile = async (newUserName) => {
const originalUserProfile = structuredClone(userProfile);
const updatedUserProfile = { ...originalUserProfile, name: newUserName }
// Optimistically update the UI
setUserProfile(updatedUserProfile);
// Try to send the database request
try {
await axios.put("/some-endpoint", updatedUserProfile);
} catch (error) {
// In case of an error go back to the previous value
setUserProfile(originalUserProfile);
console.error(error);
}
}
I am aware that I should be also checking for the status code in the response object from the post request.
Thanks for all the suggestions.
You need to sign in to view this answers