Saving Data
#
Add a Contact ModelLet's add a new database table. Open up api/db/schema.prisma
and add a Contact model after the Post model that's there now:
Prisma syntax for optional fields
To mark a field as optional (that is, allowing
NULL
as a value) you can suffix the datatype with a question mark, e.g.name String?
. This will allowname
's value to be either aString
orNULL
.
Next we create and apply a migration:
We can name this one something like "create contact".
#
Create an SDL & ServiceNow we'll create the GraphQL interface to access this table. We haven't used this generate
command yet (although the scaffold
command did use it behind the scenes):
Just like the scaffold
command, this will create two new files under the api
directory:
api/src/graphql/contacts.sdl.js
: defines the GraphQL schema in GraphQL's schema definition languageapi/src/services/contacts/contacts.js
: contains your app's business logic (also creates associated test files)
If you remember our discussion in how Redwood works with data you'll recall that queries and mutations in an SDL file are automatically mapped to resolvers defined in a service, so when you generate an SDL file you'll get a service file as well, since one requires the other.
Open up api/src/graphql/contacts.sdl.js
and you'll see the Contact
, CreateContactInput
and UpdateContactInput
types were already defined for us—the generate sdl
command introspected the schema and created a Contact
type containing each database field in the table, as well as a Query
type with a single query contacts
which returns an array of Contact
types.
The @requireAuth
string is a schema directive which says that in order to access this GraphQL query the user is required to be authenticated. We haven't added authentication yet, so this won't have any effect—anyone will be able to query it, logged in or not, because until you add authentication the function behind @requireAuth
always returns true
.
What's CreateContactInput
and UpdateContactInput
? Redwood follows the GraphQL recommendation of using Input Types in mutations rather than listing out each and every field that can be set. Any fields required in schema.prisma
are also required in CreateContactInput
(you can't create a valid record without them) but nothing is explicitly required in UpdateContactInput
. This is because you could want to update only a single field, or two fields, or all fields. The alternative would be to create separate Input types for every permutation of fields you would want to update. We felt that only having one update input type was a good compromise for optimal developer experience.
Redwood assumes your code won't try to set a value on any field named
id
orcreatedAt
so it left those out of the Input types, but if your database allowed either of those to be set manually you can updateCreateContactInput
orUpdateContactInput
and add them.
Since all of the DB columns were required in the schema.prisma
file they are marked as required in the GraphQL Types with the !
suffix on the datatype (e.g. name: String!
).
GraphQL syntax for required fields
GraphQL's SDL syntax requires an extra
!
when a field is required. Remember:schema.prisma
syntax requires an extra?
character when a field is not required.
As described in Side Quest: How Redwood Deals with Data, there are no explicit resolvers defined in the SDL file. Redwood follows a simple naming convention: each field listed in the Query
and Mutation
types in the sdl
file (api/src/graphql/contacts.sdl.js
) maps to a function with the same name in the services
file (api/src/services/contacts/contacts.js
).
So the default SDL that's created by the generators is effectively read-only: there is no way to create or update an existing record. Which means we'll need to add our own create functionality.
Psssstttt I'll let you in on a little secret: you can have Redwood create all the operators you need to perform CRUD (Create, Retrieve, Update, Delete) functions against your data automatically! But that wouldn't teach you anything, so we're doing it the hard way here. The next time you generate an SDL, try adding the
--crud
flag:
yarn rw g sdl Contact --crud
Shhhhhhhhh...
In this case we're creating a single Mutation
that we'll call createContact
. Add that to the end of the SDL file (before the closing backtick):
The createContact
mutation will accept a single variable, input
, that is an object that conforms to what we expect for a CreateContactInput
, namely { name, email, message }
. We've also added on a new directive: @skipAuth
. This one says that authentication is not required and will allow anyone to anonymously send us a message. Note that having at least one schema directive is required for each Query
and Mutation
or you'll get an error: Redwood embraces the idea of "secure by default" meaning that we try and keep your application safe, even if you do nothing special to prevent access. In this case it's much safer to throw an error than to accidentally expose all of your users' data to the internet!
Serendipitously, the default schema directive of
@requireAuth
is exactly what we want for thecontacts
query that returns ALL contacts—only we, the owners of the blog, should have access to read them all.
That's it for the SDL file, let's define the service that will actually save the data to the database. The service includes a default contacts
function for getting all contacts from the database. Let's add our mutation to create a new one:
Before we plug this into the UI, let's take a look at a nifty GUI you get just by running yarn redwood dev
.
#
GraphQL PlaygroundOften it's nice to experiment and call your API in a more "raw" form before you get too far down the path of implementation only to find out something is missing. Is there a typo in the API layer or the web layer? Let's find out by accessing just the API layer.
When you started development with yarn redwood dev
(or yarn rw dev
) you actually started a second process running at the same time. Open a new browser tab and head to http://localhost:8911/graphql This is Apollo Server's GraphQL Playground, a web-based GUI for GraphQL APIs:
Not very exciting yet, but check out that "Docs" tab on the far right:
It's the complete schema as defined by our SDL files! The Playground will ingest these definitions and give you autocomplete hints on the left to help you build queries from scratch. Try getting the IDs of all the posts in the database; type the query at the left and then click the "Play" button to execute:
The GraphQL Playground is a great way to experiment with your API or troubleshoot when you come across a query or mutation that isn't behaving in the way you expect.
#
Creating a ContactOur GraphQL mutation is ready to go on the backend so all that's left is to invoke it on the frontend. Everything related to our form is in ContactPage
so that's where we'll put the mutation call. First we define the mutation as a constant that we call later (this can be defined outside of the component itself, right after the import
statements):
We reference the createContact
mutation we defined in the Contacts SDL passing it an input
object which will contain the actual name, email and message values.
Next we'll call the useMutation
hook provided by Redwood which will allow us to execute the mutation when we're ready (don't forget the import
statement):
create
is a function that invokes the mutation and takes an object with a variables
key, containing another object with an input
key. As an example, we could call it like:
If you'll recall <Form>
gives us all of the fields in a nice object where the key is the name of the field, which means the data
object we're receiving in onSubmit
is already in the proper format that we need for the input
!
That means we can update the onSubmit
function to invoke the mutation with the data it receives:
Try filling out the form and submitting—you should have a new Contact in the database! You can verify that with Prisma Studio or GraphQL Playground if you were so inclined:
Wait, I thought you said this was secure by default and someone couldn't view all contacts without being logged in?
Remember: we haven't added authentication yet, so the concept of someone being logged in is meaningless right now. In order to prevent frustrating errors in a new application, the
@requireAuth
directive simply returnstrue
until you setup an authentication system. At that point the directive will use real logic for determining if the user is logged in or not and behave accordingly.
#
Improving the Contact FormOur contact form works but it has a couple of issues at the moment:
- Clicking the submit button multiple times will result in multiple submits
- The user has no idea if their submission was successful
- If an error was to occur on the server, we have no way of notifying the user
Let's address these issues.
#
Disable Save on LoadingThe useMutation
hook returns a couple more elements along with the function to invoke it. We can destructure these as the second element in the array that's returned. The two we care about are loading
and error
:
Now we know if the database call is still in progress by looking at loading
. An easy fix for our multiple submit issue would be to disable the submit button if the response is still in progress. We can set the disabled
attribute on the "Save" button to the value of loading
:
It may be hard to see a difference in development because the submit is so fast, but you could enable network throttling via the Network tab Chrome's Web Inspector to simulate a slow connection:
You'll see that the "Save" button become disabled for a second or two while waiting for the response.
#
Notification on SaveNext, let's show a notification to let the user know their submission was successful. Redwood includes react-hot-toast to quickly show a popup notification on a page.
useMutation
accepts an options object as a second argument. One of the options is a callback function, onCompleted
, that will be invoked when the mutation successfully completes. We'll use that callback to invoke a toast()
function which will add a message to be displayed in a <Toaster> component.
Add the onCompleted
callback to useMutation
and include the <Toaster> component in our return
, just before the <Form>:
You can read the full documentation for Toast here.
#
Displaying Server ErrorsNext we'll inform the user of any server errors. So far we've only notified the user of client errors: a field was missing or formatted incorrectly. But if we have server-side constraints in place <Form>
can't know about those, but we still need to let the user know something went wrong.
We have email validation on the client, but any developer worth their silicon knows never trust the client. Let's add the email validation into the api side as well to be sure no bad data gets into our database, even if someone somehow bypassed our client-side validation (l33t hackers do this all the time).
No server-side validation for some fields?
Why don't we need server-side validation for the existence of name, email and message? Because GraphQL is already doing that for us! You may remember the
String!
declaration in our SDL file for theContact
type: that adds a constraint that those fields cannot benull
as soon as it arrives on the api side. If it is, GraphQL would reject the request and throw an error back to us on the client.We've even got another layer of validation: because name, email and message were set as required in our schema.prisma file, the database itself will prevent any
null
s from being recorded. It's like if you decided to run out onto the field in the middle of a sporting event wearing your favorite Redwood t-shirt: even if you somehow made it past the security guard (GraphQL), once you get out there you're going to have to deal with actual professional athletes (the database). They've spent their whole life training to run faster and pick up heavier things than you. You won't make it very far if they decide to stop you!
We talked about business logic belonging in our services files and this is a perfect example. Let's add a validate
function to our contacts
service:
So when createContact
is called it will first validate the inputs and only if no errors are thrown will it continue to actually create the record in the database.
We already capture any existing error in the error
constant that we got from useMutation
, so we could manually display an error box on the page somewhere containing those errors, maybe at the top of the form (you can put this in your contact form, but we're about to change it to something even better):
To get a server error to fire, let's remove the email format validation so that the client-side error isn't shown:
If you made the change above and then try to fill out the form with an invalid email address:
It ain't pretty, but it works. It would be nice if the field itself was highlighted like it was when the inline validation was in place...
Remember when we said that <Form>
had one more trick up its sleeve? Here it comes!
Remove the inline error display (if you added it, the block starting with { error && ...}
) and replace it with <FormError>
, passing the error
constant we got from useMutation
and a little bit of styling to wrapperStyle
(don't forget the import
). We'll also pass error
to <Form>
so it can setup a context:
Now submit a message with an invalid email address:
We get that error message at the top saying something went wrong in plain English and the actual field is highlighted for us, just like the inline validation! The message at the top may be overkill for such a short form, but it can be key if a form is multiple screens long; the user gets a summary of what went wrong all in one place and they don't have to resort to hunting through a long form looking for red boxes. You don't have to use that message box at the top, though; just remove <FormError>
and the field will still be highlighted as expected.
The fact that the error message was also attached to the form field is enabled by the format of the error that we threw in the Contacts service:
That second argument is an object with a key, messages
, that points to another object with keys the same as the name
of the input/label and values that are an array of strings containing the actual error message. All of these are also combined into the content of <FormError>
.
<FormError>
styling options
<FormError>
has several styling options which are attached to different parts of the message:
wrapperStyle
/wrapperClassName
: the container for the entire messagetitleStyle
/titleClassName
: the "Can't create new contact" titlelistStyle
/listClassName
: the<ul>
that contains the list of errorslistItemStyle
/listItemClassName
: each individual<li>
around each error
#
One more thing...Since we're not redirecting after the form submits, we should at least clear out the form fields. This requires we get access to a reset()
function that's part of React Hook Form, but we don't have access to it with the basic usage of <Form>
(like we're currently using).
Redwood includes a hook called useForm()
(from React Hook Form) which is normally called for us within <Form>
. In order to reset the form we need to invoke that hook ourselves. But the functionality that useForm()
provides still needs to be used in Form
. Here's how we do that.
First we'll import useForm
:
And now call it inside of our component:
Finally we'll tell <Form>
to use the formMethods
we just got from useForm()
instead of doing it itself:
Now we can call reset()
on formMethods
after we call toast()
:
You can put the email validation back into the
<TextField>
now, but you should leave the server validation in place, just in case.
Here's the entire page:
That's it! React Hook Form provides a bunch of functionality that <Form>
doesn't expose. When you want to get to that functionality you can call useForm()
yourself, but make sure to pass the returned object (we called it formMethods
) as a prop to <Form>
so that the validation and other functionality keeps working.
You may have noticed that the onBlur form config stopped working once you started calling
useForm()
yourself. That's because Redwood callsuseForm()
behind the scenes and automatically passes it theconfig
prop that you gave to<Form>
. Redwood is no longer callinguseForm()
for you so if you need some options passed you need to do it manually:
The public site is looking pretty good. How about the administrative features that let us create and edit posts? We should move them to some kind of admin section and put them behind a login so that random users poking around at URLs can't create ads for discount pharmaceuticals.