Skip to content

useGraphQuery/Mutation #51

@fouad

Description

@fouad

Note: there's an ongoing conversation in #24 about promises/async functions in Hooks + Suspense

Here's a rough idea for exposing lightweight Hooks for GraphQL:

import useGraphQuery from '@rehooks/use-graph-query'
import ProfileSkeleton from './profile-skeleton'
import gql from 'graphql-tag'

export default function ProfileDetail(props) {
  const [{ data, loading }] = useGraphQuery(profileQuery(props.id))

  if (loading) return <ProfileSkeleton />

  return <div>Name: {data.firstName} {data.lastName}</div>
}

export function profileQuery(id) {
  return gql`
    query {
      user(id: ${id}) {
        firstName
        lastName
      }
    }
  `
}

And then for mutations:

import useInputValue from '@rehooks/input-value'
import useGraphQuery from '@rehooks/use-graph-query'
import useGraphMutation from '@rehooks/use-graph-mutation'

import FormError from './form-error'
import FormSkeleton from './form-skeleton'
import { profileQuery } from './profile-detail'

export default function ProfileForm({ id } {
  const [{ data, loading, error }] = useGraphQuery(profileQuery(props.id))
  const [saveResult, onSave] = useGraphMutation(saveProfileMutation())

  if (loading) return <FormSkeleton />

  const firstNameInput = useInputValue(data.firstName)
  const lastNameInput = useInputValue(data.lastName)

  const onSubmit = evt => {
    evt.preventDefault()

    const firstName = firstNameInput[0]
    const lastName = lastNameInput[0]

    onSave({ variables: { id, firstName, lastName } })
  }

  return (
    <form onSubmit={onSubmit}>
      <FormError error={error || saveResult.error} />
      <input type="text" {...firstNameInput} />
      <input type="text" {...lastNameInput} />
      <input type="submit" value="Submit" />
    </form>
  )
}

export function saveProfileMutation() {
  return gql`
    mutation SaveProfile($id: String!, $firstName: String, $lastName: String) {
      updateProfile(profileId: $id, firstName: $firstName, lastName: $lastName) {
        id
        firstName
        lastName
      }
    }
  `
}

Author's note: I went with [value, fn] for useGraphQuery to account for fetchMore, refetch and other pagination handling patterns.

This might turn into two-destructurable objects like [{ loading, data }, { refetch, fetchMore }]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions