0.2.1 • Published 7 years ago
use-graphql-request v0.2.1
use-graphql-request
a minimal hook for querying graphql endpoint from react
Install
npm i use-graphql-request
# also install peer deps if you don't already have them
npm i use-graphql-request graphql-request react graphqlAPI
Library offers 3 components:
UseGraphQLProvider
Register a client-a graphql-request instance to put into react context.
useQuery
Runs a GQL query upon mount and whenever props change.
useMutation
Returns a function and state to run GQL mutations.
Code samples
all assume this wrapper:
import { UseGraphQLProvider } from 'graphql-request'
const rootElement = document.getElementById('root')
ReactDOM.render(
  <UseGraphQLProvider
    client={new GraphQLClient('https://api.graph.cool/simple/v1/movies')}
  >
    <App />
  </UseGraphQLProvider>,
  rootElement
)Sample Query
import gql from 'graphql-tag'
import { useGraphQL } from 'graphql-request'
function App() {
  const { data, loading, refetch } = useGraphQL<{ Movie: any }>(gql`
    {
      Movie(title: "Inception") {
        releaseDate
        actors {
          name
        }
      }
    }
  `)
  console.log('resp', data) // logs undefined and then {"Movie":{"releaseDate":"2010-08-28T20:00:00.000Z","actors":[{"name":"Leonardo DiCaprio"},{"name":"Ellen Page"},{"name":"Tom Hardy"},{"name":"Joseph Gordon-Levitt"},{"name":"Marion Cotillard"}]}}
  return (
    <>
      <div className="App">{JSON.stringify(data)}</div>
      <button disabled={loading} onClick={refetch}>
        refetch
      </button>
    </>
  )
}Sample mutation
const [{ loading }, execute] = useMutation(gql`
  mutation($id: Float!, $name: String!) {
    book(bookId: $id) {
      edit(name: $name) {
        id
        name
      }
    }
  }
`)
return (
  <button
    disabled={loading}
    onClick={async () => {
      const data = await execute({
        id: 2,
        name: 'Lord of the Rings III'
      })
      console.log('App -> mutated', data)
    }}
  >
    mutate
  </button>
)Is this a replacement for apollo/relay?
No, it's only suitable for small and simple apps-see FAQ on graphql-request. It doesn't have any caching, no links, doesn't support SSR, no complex features.