...

/

Feedback and Validation using Mutations

Feedback and Validation using Mutations

Learn how to get feedback from the user and validate your input data when using GraphQL mutations in a React application.

Getting feedback

In the last lesson, we learned how to make a form to submit new books to our database. But the form doesn’t provide any confirmation that the data has been passed to the server. It would be better if the form gave us some feedback when the book is created. We can do that by changing the WrappedBookForm to the following:

function CreateForm() {
const [createBookMut, { data, called, loading, error }] = useCreateBookMutation();
const createBook = ({ title }: { title: string }) => {
createBookMut({
variables: { title },
});
};
return (
<>
<Form onSubmit={createBook} />
{
called && !loading && !error && (
<div className="text-green-500 mt-4">Book created successfully!</div>
)
}
</>
);
}
New CreateForm function

The useCreateBookMutation function’s second element returns an object that lets us check to see if the mutation has been called. We use this property along with the loading and error properties to make sure these conditions have been met:

  1. The mutation has been called.

  2. The mutation is is not currently loading. ...