@iwatakeshi/apollo-next
v0.2.3
Published
Utilities to integrate Apollo and Next.js.
Downloads
8
Readme
apollo-next
Utilities to integrate Apollo and Next.js.
Usage
- Install
apollo-next
:
npm add @iwatakeshi/apollo-next graphql @apollo/client
- Create a custom Apollo client
export const createApolloClient = () =>
new ApolloClient({
ssrMode: typeof window === "undefined",
// ...
});
- Set the
ApolloProvider
in_app
file and initialize Apollo.
import { ApolloProvider } from "@apollo/client";
import { useApollo } from "@iwatakeshi/apollo-next";
// Import your custom client
import { createApolloClient } from "../utils/client.apollo";
function MyApp({ Component, pageProps }) {
return (
<ApolloProvider client={useApollo(createApolloClient(), pageProps)}>
<Component {...pageProps} />
</ApolloProvider>
);
}
export default MyApp;
- Use it in your static or server-side rendered pages.
import { useQuery } from "@apollo/client";
import { GetStaticProps } from "next";
import { withApollo } from "@iwatakeshi/apollo-next";
// Import your custom client
import { createApolloClient } from "../utils/client.apollo";
export default function MyPage() {
const { data } = useQuery(/* ... */);
return <div>{/* ... */}</div>;
}
// Wrap `getStaticProps` or `getServerSideProps` with Apollo
export const getStaticProps = withApollo<GetStaticProps>(
createApolloClient(),
async ({ client }) => {
const { data } = await client.query(/*...*/);
return {
props: {
data,
},
};
}
);
// Or pass a function to access the context: (context) => createApolloClient()
export const getStaticProps = withApollo<GetStaticProps>(
(context) => createApolloClient(),
async ({ client }) => {
const { data } = await client.query(/*...*/);
return {
props: {
data,
},
};
}
);