I have this callback function that is called from a child component that updates the form (I’m using react-hook-form
) of the parent component
const goalSetter = useMemo(() => {
return (value: string[]) => {
const goals: Goals[] = value
.map((goal) => stringToEnumValue(goal, Goals))
.filter((v) => !!v) as Goals[];
form.setValue('goals', [...goals]);
await updateUserData('goals');
};
}, []);
Problem is the updateUserData
function takes a long time to execute and slows down the app. So, it takes about a second to see the visual feedback in the UI.
updateUserData:
const updateUserData = async (field: ProfileField) => {
await form.trigger(field);
if (form.formState.isValid) {
await updateUser(userDataSchema.cast(form.getValues()));
} else {
form.setError(field, {
type: 'validation-error',
message: 'Please enter a valid input',
});
console.log('form is not valid');
}
};
I have tried memoizing the functions but that barely makes a difference. How can I refactor this to do the update part in the background and increase the responsiveness ?
Any help is welcome. Thanks