Submit.js 1.7 KB
Newer Older
1
import { gql, useMutation } from '@apollo/client'
2

3 4 5 6 7 8 9 10 11 12 13
const CREATE_POST_MUTATION = gql`
  mutation createPost($title: String!, $url: String!) {
    createPost(title: $title, url: $url) {
      id
      title
      votes
      url
      createdAt
    }
  }
`
14

15 16
const Submit = () => {
  const [createPost, { loading }] = useMutation(CREATE_POST_MUTATION)
17

J
Joe Haddad 已提交
18
  const handleSubmit = (event) => {
19 20
    event.preventDefault()
    const form = event.target
21
    const formData = new window.FormData(form)
22 23
    const title = formData.get('title')
    const url = formData.get('url')
24
    form.reset()
25 26 27

    createPost({
      variables: { title, url },
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
      update: (cache, { data: { createPost } }) => {
        cache.modify({
          fields: {
            allPosts(existingPosts = []) {
              const newPostRef = cache.writeFragment({
                data: createPost,
                fragment: gql`
                  fragment NewPost on allPosts {
                    id
                    type
                  }
                `,
              })
              return [newPostRef, ...existingPosts]
            },
43 44
          },
        })
45
      },
46
    })
47 48 49 50
  }

  return (
    <form onSubmit={handleSubmit}>
51
      <h1>Submit</h1>
52 53 54
      <input placeholder="title" name="title" type="text" required />
      <input placeholder="url" name="url" type="url" required />
      <button type="submit" disabled={loading}>
55 56
        Submit
      </button>
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
      <style jsx>{`
        form {
          padding-bottom: 20px;
          margin-bottom: 20px;
        }
        h1 {
          font-size: 20px;
        }
        input {
          display: block;
          margin-bottom: 10px;
        }
      `}</style>
    </form>
  )
}

74
export default Submit