Following Manage Local State Example, I get @client is undefined
July 6, 2020 at 12:11amFollowing Manage Local State Example, I get @client is undefined
July 6, 2020 at 12:11amHello all, I am very new to all this. I followed this example but I get
unknown directive
. I am just trying to figure out how to have some local data in my app. I tried adding the cache
section to my create.js
file but then I got cache is undefined
.withApollo.js
import React from "react";import Head from "next/head";import { ApolloProvider } from "@apollo/react-hooks";import createApolloClient from "./create";let apolloClient = null;/*** Creates and provides the apolloContext* to a next.js PageTree. Use it by wrapping* your PageComponent via HOC pattern.* @param {Function|Class} PageComponent* @param {Object} [config]* @param {Boolean} [config.ssr=true]*/export function withApollo(PageComponent, { ssr = true } = {}) {const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {const client = apolloClient || initApolloClient(apolloState);return (<ApolloProvider client={client}><PageComponent {...pageProps} /></ApolloProvider>);};// Set the correct displayName in developmentif (process.env.NODE_ENV !== "production") {const displayName =PageComponent.displayName || PageComponent.name || "Component";if (displayName === "App") {console.warn("This withApollo HOC only works with PageComponents.");}WithApollo.displayName = `withApollo(${displayName})`;}if (typeof window === "undefined" || PageComponent.getInitialProps) {WithApollo.getInitialProps = async (ctx) => {const { AppTree } = ctx;// Initialize ApolloClient, add it to the ctx object so// we can use it in `PageComponent.getInitialProp`.const apolloClient = await (ctx.apolloClient = initApolloClient({},ctx.req.headers.cookie));// Run wrapped getInitialProps methodslet pageProps = {};if (PageComponent.getInitialProps) {pageProps = await PageComponent.getInitialProps(ctx);}// Only on the server:if (typeof window === "undefined") {// When redirecting, the response is finished.// No point in continuing to renderif (ctx.res && ctx.res.finished) {return pageProps;}// Only if ssr is enabledif (ssr) {try {// Run all GraphQL queriesconst { getDataFromTree } = await import("@apollo/react-ssr");await getDataFromTree(<AppTreepageProps={{...pageProps,apolloClient,}}/>);} catch (error) {// Prevent Apollo Client GraphQL errors from crashing SSR.// Handle them in components via the data.error prop:// https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-errorconsole.error("Error while running `getDataFromTree`", error);}// getDataFromTree does not call componentWillUnmount// head side effect therefore need to be cleared manuallyHead.rewind();}}// Extract query data from the Apollo store// @ts-ignoreconst apolloState = apolloClient.cache.extract();return {...pageProps,apolloState,};};}return WithApollo;}/*** Always creates a new apollo client on the server* Creates or reuses apollo client in the browser.* @param {Object} initialState*/function initApolloClient(initialState = {}, cookie = "") {// 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 createApolloClient(initialState, cookie)}// Reuse client on the client-sideif (!apolloClient) {// @ts-ignoreapolloClient = createApolloClient(initialState)}return apolloClient}
create.js
```import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import Cookies from 'js-cookie';
import { serverUrl } from '../config';
import { resolvers, typeDefs } from "../src/graphql/resolvers";
export default function createApolloClient(initialState, ctx) {
// The
ctx
(NextPageContext) will only be present on the server.
// use it to extract auth headers (ctx.req) or similar.const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const token = Cookies.get("XSRF-TOKEN");
// return the headers to the context so httpLink can read them
return {headers: {...headers,"Access-Control-Allow-Credentials": true,...(token ? { "X-CSRF-TOKEN": `${token}` } : {}),...(token ? { "authorization": `Bearer ${token}` } : {}),},};
});
const httpLink = createHttpLink({
uri: serverUrl,
credentials: 'include',
});
const client = new ApolloClient({
ssrMode: Boolean(ctx),
link: authLink.concat(httpLink),
connectToDevTools: true,
cache: new InMemoryCache().restore(initialState),
});
return client;
}
In my login page I have
const [loginUser, { loading }] = useMutation(LOGIN_USER, {
errorPolicy: 'all',
onCompleted: (res) => {
if (res.login) {
client.writeData({ data: { isLoggedIn: true } });
Router.push('/');
} else {
setState((prevState) => ({
...prevState,
loginError: true,
}));
}
},
});
which does redirect to index page but I am still trying to figure out how I can access the ```isLoggedIn``` variable.### index.js
```import gql from "graphql-tag";export const typeDefs = gql`extend type Query {isLoggedIn: Boolean!}`;export const resolvers = {};
July 6, 2020 at 12:12am