Apollo GraphQL
Installation
- npm
- Yarn
npm install @nhost/react @nhost/react-apollo @apollo/client graphql
yarn add @nhost/react @nhost/react-apollo @apollo/client graphql
Initializing
Wrap the React app with the NhostApolloProvider
and make sure the NhostApolloProvider
is nested inside the NhostProvider
.
This way, the correct authentication headers are set automatically for GraphQL requests being made by Apollo.
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import { NhostApolloProvider } from '@nhost/react-apollo'
import { NhostClient, NhostProvider } from '@nhost/react'
const nhost = new NhostClient({
subdomain: '<app-subdomain>',
region: '<app-region>'
})
ReactDOM.render(
<React.StrictMode>
<NhostProvider nhost={nhost}>
<NhostApolloProvider nhost={nhost}>
<App />
</NhostApolloProvider>
</NhostProvider>
</React.StrictMode>,
document.getElementById('root')
)
Usage
You can now use all Apollo hooks (queries, mutations, subscriptions) and the correct authentication headers will automatically be set based on the authentication status of the user.
Example
import { gql, useQuery } from '@apollo/client'
import { useAuthenticated } from '@nhost/react'
const GET_BOOKS = gql`
query Books {
books {
id
title
}
}
`
export const BooksQuery = () => {
const isAuthenticated = useAuthenticated()
const { loading, data, error } = useQuery(GET_BOOKS)
if (loading) {
return <div>Loading...</div>
}
if (!isAuthenticated) {
return <div>You must be authenticated to see this page</div>
}
if (error) {
return <div>Error in the query {error.message}</div>
}
return (
<div>
<ul>
{data?.books.map((book) => (
<li key={book.id}>{book.name}</li>
))}
</ul>
</div>
)
}
Hooks
useAuthQuery
The useAuthQuery
hook works just like Apollo's useQuery
except the query will be skipped if the user is not authenticated.
Read more
Learn more about the GraphQL Apollo Client.