menu

Apollo

A community of developers, designers and others who love Apollo and GraphQL. 🚀

Channels
# All channels
view-forward
# General
view-forward
# Apollo Angular
view-forward
# Announcements
view-forward
# Apollo Android
view-forward
# Apollo Client
view-forward
# Apollo iOS
view-forward
# Apollo Link
view-forward
# Apollo Link Rest
view-forward
# Local State
view-forward
# Apollo Studio
view-forward
# Apollo Server
view-forward
# Apollo Tooling
view-forward
# Contributing
view-forward
# Docs
view-forward
# Events
view-forward
# GraphQL Tools
view-forward
# Jobs
view-forward
# Random
view-forward
# React Apollo
view-forward
# Showcase
view-forward
# Subscriptions
view-forward
# Testing
view-forward
# Vue Apollo
view-forward
Team

Following Manage Local State Example, I get @client is undefined

July 6, 2020 at 12:11am

Following Manage Local State Example, I get @client is undefined

July 6, 2020 at 12:11am
Hello 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 development
if (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 methods
let 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 render
if (ctx.res && ctx.res.finished) {
return pageProps;
}
// Only if ssr is enabled
if (ssr) {
try {
// Run all GraphQL queries
const { getDataFromTree } = await import("@apollo/react-ssr");
await getDataFromTree(
<AppTree
pageProps={{
...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-error
console.error("Error while running `getDataFromTree`", error);
}
// getDataFromTree does not call componentWillUnmount
// head side effect therefore need to be cleared manually
Head.rewind();
}
}
// Extract query data from the Apollo store
// @ts-ignore
const 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-side
if (!apolloClient) {
// @ts-ignore
apolloClient = 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
const IS_LOGGED_IN = gqlquery isLoggedIn { isLoggedIn };
```
import gql from "graphql-tag";
export const typeDefs = gql`
extend type Query {
isLoggedIn: Boolean!
}
`;
export const resolvers = {};

July 6, 2020 at 12:12am
I tried to edit the code formatting but it keeps saying "failed to fetch" ... kind of doubting my choice of tech stack now
  • reply
  • like