我正在构建一个 next.js 应用程序,我打算在其中使用几个 graphql-apis。在我的组件中使用useQuery
from时,我想传递一个上下文。@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
}
我的示例组件如下所示:
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'
某个地方看到……但什么也没有。有人可以帮助我吗?