lfades / next-with-apollo

Apollo HOC for Next.js
MIT License
765 stars 79 forks source link

How to acces react context in HOC withApollo example? #133

Open kaloraat opened 4 years ago

kaloraat commented 4 years ago

Hi The withApollo HOC example works perfectly but I need to send authtoken in headers, which is coming from react context (I am using firebase authtoken, not localStorage or cookie) which is available in my context. Can you please help how I can access context in this withApollo HOC example?

Later I will need to add more configuration such as webSocket link for subscription etc

This is my code, Only thing I have added is import Context so that I can access token from context and send in headers. Thx

import React, { useContext } from "react"; // TO ACCESS CONTEXT AUTHTOKEN
import withApollo from "next-with-apollo";
import ApolloClient, { InMemoryCache } from "apollo-boost";
import { ApolloProvider } from "@apollo/react-hooks";
import { Context } from "../context"; // CONTEXT

// here i would like to access state.user.token so that i can send in headers
const { state } = useContext(Context);
const { user } = state; // user.token

export default withApollo(
  ({ initialState }) => {
    return new ApolloClient({
      uri: process.env.GRAPHQL,
      cache: new InMemoryCache().restore(initialState || {}),
      headers: {
        authtoken: "", // GET AUTHTOKEN FROM CONTEXT AND SEND IN HEADERS
      },
    });
  },
  {
    render: ({ Page, props }) => {
      return (
        <ApolloProvider client={props.apollo}>
          <Page {...props} />
        </ApolloProvider>
      );
    },
  }
);
lfades commented 4 years ago

@kaloraat You can't use React context here, as that's not even a component, and it gets created outside one, what you could do is import firebase and use one of its APIs to get the token without using a React hook.

Keep in mind that if the token is not available in the server (cookies is the only way to make it available for the server), then you'll only be able to add authentication for client-side rendering

kaloraat commented 4 years ago

@kaloraat You can't use React context here, as that's not even a component, and it gets created outside one, what you could do is import firebase and use one of its APIs to get the token without using a React hook.

Keep in mind that if the token is not available in the server (cookies is the only way to make it available for the server), then you'll only be able to add authentication for client-side rendering

Ya I thought so, thanks for your response