Skip to main content

Forms

General

For implementing forms, we use a custom useForm hook that manages form's state. It supports both dynamic and static fields, and tracks errors and changed values.

useForm hook

Note: Below is the embedded storybook documentation for useForm.

Resetting state after a form submissions

After a form was submitted, we usually want to reset its local React state. But we need to do so only after the data that the form depends on has reloaded, otherwise we'll re-initialise the form with stale data.

React Query has a useful mechanism for this: awaiting query invalidations. When we return the promise of a query invalidation, it will only resolve once all affected queries have reloaded, which is the perfect time to reset our form state, allowing it to pick up the latest server data:

Mutation hook example:

const mutation = useMutation(updatePlaylistContent(playlistId), {
onSuccess: () => {
return Promise.all([
queryClient.invalidateQueries(ALL_ASSETS),
queryClient.invalidateQueries(ALL_PLAYLISTS),
]).then(() => {
setSuccessAlert({
title: t('alert_playlist_updated_successfully'),
});
});
},
});

With that, we can await the mutation in our submit handler and reset the form at just the right time:

async function saveContentChanges() {
await updatePlaylistContent(newData);
form.reset();
}