Передача контекста из useQuery клиенту Apollo
Я создаю приложение next.js, в котором собираюсь использовать несколько графических API-интерфейсов. Я хотел бы передать контекст при использованииuseQuery
от @apollo/react-hooks
в моих компонентах. На данный момент мой клиент выглядит так:
import { ApolloClient } from '@apollo/client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { ApolloLink } from 'apollo-link'
let apolloClient
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: new ApolloLink((operation) => {
console.log(operation.getContext())
return new HttpLink({
uri: 'http://localhost:1337/graphql', // Server URL (must be absolute)
credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
}).request(operation)
}),
cache: new InMemoryCache(),
})
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient()
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here
if (initialState) {
_apolloClient.cache.restore(initialState)
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient
return _apolloClient
}
export function useApollo(initialState) {
const store = useMemo(() => initializeApollo(initialState), [initialState])
return store
}
и мой компонент Sample выглядит так:
import gql from 'graphql-tag'
import { useQuery } from '@apollo/react-hooks'
import { initializeApollo } from '../lib/apolloClient'
interface Props {}
export const STRAPI = gql`
query {
questions {
question
}
}
`
const Sample = (props: Props) => {
const {
loading: strapiLoading,
error: strapiError,
data: strapiData,
} = useQuery(STRAPI, {
context: {
api: 'strapi',
},
notifyOnNetworkStatusChange: true,
})
return (
<div>
<h1>{strapiData.questions[0].question}</h1>
</div>
)
}
export async function getStaticProps() {
const apolloClient = initializeApollo()
await apolloClient.query({
query: STRAPI,
})
return {
props: {
initialApolloState: apolloClient.cache.extract(),
},
unstable_revalidate: 1,
}
}
export default Sample
В клиенте я пытаюсь распечатать контекст с помощью console.log(operation.getContext())
и я ожидал увидеть 'context: 'api'
где-то... но ничего. Кто-нибудь может мне помочь?