Redwood Forms: Input Validation, Type errors, Schema Validation -- How To Example

If you are using Redwood Forms and have experienced any <Input /> error about “Expected type X …”, then this example is for you.

Input types validate the value from a user at the time of input. The GraphQL mutation validates the data type it receives from the DOM. But what is missing is actually casting the input type into the data type expected by GraphQL. (Yes, this is confusing indeed. Regardless of input type validation, your form is simply returning a string. :face_with_raised_eyebrow:)

Here’s the way forward via an example from our own @rob:

Ahh yes, the good ol’ DOM. All input fields return strings, so you’ll need to transform those into your desired datatype before calling your mutation. The simplest way to do this currently is in your onSubmit handler where you get the form field values from Redwood Form as an object and you then call your mutation with that object.

In the scaffolded code that might look something like:

// web/src/componets/NewPost/NewPost.js

const NewPost = () => {
  const [createPost, { loading, error }] = useMutation(CREATE_STATE_MUTATION)

  const onSave = (input) => {
    const castInput = { 
      city,
      state, 
      index: parseFloat(index), 
      grocery: parseFloat(grocery),
      // ...
    }
    createPost({ variables: { castInput } })
  }

  return (
    // ...
  )
}

References

1 Like