lightweight react hooks for querying graphql endpoint from react
MIT License
lightweight react hooks for querying graphql endpoint from react
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
Library offers 3 components:
Register a client-a graphql-request
instance to put into react context.
Runs a GQL query upon mount and whenever props change.
Returns a function and state to run GQL mutations.
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
)
import gql from 'graphql-tag'
import { useQuery } from 'graphql-request'
function App() {
const { data, loading, refetch } = useQuery<{ 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>
</>
)
}
import gql from 'graphql-tag'
import { useMutation } from 'graphql-request'
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>
)
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.