0.2.1 • Published 5 years ago

use-graphql-request v0.2.1

Weekly downloads
1
License
MIT
Repository
-
Last release
5 years ago

Build Status Coverage Status MIT license

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 graphql

API

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

Edit react-hooks-1

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.

0.2.1

5 years ago

0.2.0

5 years ago

0.1.0

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

6 years ago

0.0.1

6 years ago