简体   繁体   English

为 NextJS 实现 Apollo 客户端,但无法读取未定义的属性“WebSocket”

[英]Implementing Apollo Client for NextJS but getting Cannot read property 'WebSocket' of undefined

Decided to switch from normal React to NextJS after watching various videos and reading articles.在看了各种视频和阅读文章后,决定从普通的 React 切换到 NextJS。 I'm currently trying to implement Apollo Client but am getting this (title) error and was hoping to get some help.我目前正在尝试实现 Apollo Client,但收到此(标题)错误并希望获得一些帮助。 The way my withData is currently set is我的 withData 当前设置的方式是

import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { hasSubscription } from '@jumpn/utils-graphql';
import * as AbsintheSocket from '@absinthe/socket';
import withApollo from 'next-with-apollo';
import { createAbsintheSocketLink } from '@absinthe/socket-apollo-link';
import { Socket as PhoenixSocket } from 'phoenix';

let apolloClient = null;

const HTTP_ENDPOINT = 'http://localhost:4000/api/v1/graphiql';

const WS_ENDPOINT = 'ws://localhost:4000/api/v1/socket';

const httpLink = createHttpLink({
    url: HTTP_ENDPOINT
});

const socketLink = createAbsintheSocketLink(AbsintheSocket.create(new PhoenixSocket(WS_ENDPOINT)));

const authLink = setContext((_, { headers }) => {
    const token = localStorage.getItem('auth-item');
    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : ''
        }
    };
});

const link = new ApolloLink.split(
    (operation) => hasSubscription(operation.query),
    socketLink,
    authLink.concat(httpLink)
);

const create = (initialState) => {
    return new ApolloClient({
        link: link,
        cache: new InMemoryCache().restore(initialState || {})
    });
};

const initApollo = (initialState) => {
    // Make sure to create a new client for every server-side request so that data
    // isn't shared between connections (which would be bad)
    if (typeof window === 'undefined') {
        return create(initialState);
    }

    // Reuse client on the client-side
    if (!apolloClient) {
        apolloClient = create(initialState);
    }

    return apolloClient;
};

export default withApollo(initApollo);

All help is appreciated to understand what I did wrong and what is a better approach should there be one.感谢所有帮助,以了解我做错了什么,如果有更好的方法是什么。

The issue is because nextJs will run the code above in the server and WebSocket is a property that exists only in the browser, to get this fixed you can do:问题是因为 nextJs 将在服务器中运行上面的代码,并且WebSocket是仅存在于浏览器中的属性,要修复此问题,您可以执行以下操作:

const socketLink =
  process.browser &&
  createAbsintheSocketLink(
    AbsintheSocket.create(
      new PhoenixSocket(WS_URI)
    )
  )

By checking for process.browser you make sure that this function is executed only on client-side.通过检查process.browser ,您可以确保此 function 仅在客户端执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM