[英]Document is undefined when using apollo query with next.js getServerSideProps
I am trying to use getServerSideProps
to fetch a query every time this component is rendered using apollo
and next.js
每次使用
apollo
和next.js
呈现此组件时,我都尝试使用getServerSideProps
来获取查询
export async function getServerSideProps(context) {
const { data } = await client.query({
query: GET_AUTHED_USER
})
return {
props: { user: data.getAuthedUser },
}
}
const Profile = ({ user }) => {
const router = useRouter();
// const [state, setState] = useState(JSON.parse(router.query.currentUser));
const [state, setState] = useState(user);
console.log(state)
...
APOLLO CONFIG阿波罗配置
import { ApolloClient, InMemoryCache, ApolloLink } from '@apollo/client';
import { getCookie } from './utils/functions';
import { setContext } from '@apollo/client/link/context';
import { createUploadLink } from 'apollo-upload-client';
const authLink = setContext((_, { headers }) => {
// get the authentication token from storage if it exists
const token = getCookie('JWT');
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? token : '',
}
}
});
const httpLink = createUploadLink({
uri: 'http://localhost:5000/graphql',
});
const client = new ApolloClient({
uri: 'http://localhost:5000/graphql',
cache: new InMemoryCache(),
link: ApolloLink.from([authLink, httpLink])
});
export default client;
currently, when visiting the /profile
page I receive the error:目前,当访问
/profile
页面时,我收到错误:
Server Error
Error: document is not defined
Does anyone have any insight on how to resolve this or suggest a valid work around?有没有人对如何解决这个问题有任何见解或建议有效的解决方法?
appolo/client is a client side library. appolo/client 是一个客户端库。 getServersideProps execute in server side.
getServersideProps 在服务器端执行。 document doesn't exist in server side.
文档在服务器端不存在。 It will only work within client side.
它只能在客户端工作。
Workaround 1:解决方法 1:
You can use swr .您可以使用swr 。 swr is for client side data fetch.
swr 用于客户端数据获取。 so you don't need getServerSideProps.
所以你不需要getServerSideProps。
Workaround 2:解决方法 2:
You can use apollo-server .您可以使用apollo-server 。 Then you can call apollo-server function in getServerSideProps as apollo-server is for server side calling.
然后您可以在 getServerSideProps 中调用 apollo-server 函数,因为 apollo-server 用于服务器端调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.