Introduction to GraphQL
GraphQL is an API query language that fetches data based only on what the client application needs. It solves the problem of clients fetching unnecessary data thus making APIs more scalable. The precision in data fetching is the power of GraphQL. Find out more on the official or later.
Client Components
This data fetching method applies to client components, in the event you wish to use state or context depending on your use case.
We begin by creating a provider for Apollo that passes the client to the hooks.
// ./apollo-wrapper.tsx
"use client";
import { ApolloLink, HttpLink } from "@apollo/client";
import {
ApolloClient,
ApolloNextAppProvider,
InMemoryCache,
SSRMultipartLink,
} from "@apollo/experimental-nextjs-app-support";
function makeClient() {
const httpLink = new HttpLink({
uri: "https://rickandmortyapi.com/graphql",
});
return new ApolloClient({
cache: new InMemoryCache(),
link:
typeof window === "undefined"
? ApolloLink.from([
// in a SSR environment, if you use multipart features like
// @defer, you need to decide how to handle these.
// This strips all interfaces with a `@defer` directive from your queries.
new SSRMultipartLink({
stripDefer: true,
}),
httpLink,
])
: httpLink,
});
}
export function ApolloWrapper({ children }: React.PropsWithChildren) {
return (
<ApolloNextAppProvider makeClient={makeClient}>
{children}
</ApolloNextAppProvider>
);
}
Let’s break it down step by step:
We create an HTTP link that Apollo Client uses to send queries to the endpoint we specify
Then we define a function called makeClient which creates an Apollo Client instance for SSR and client environments.
function makeClient() {
const httpLink = new HttpLink({
uri: "https://rickandmortyapi.com/graphql",
});
return new ApolloClient({
cache: new InMemoryCache(),
link:
typeof window === "undefined"
? ApolloLink.from([
// in a SSR environment, if you use multipart features like
// @defer, you need to decide how to handle these.
// This strips all interfaces with a `@defer` directive from your queries.
new SSRMultipartLink({
stripDefer: true,
}),
httpLink,
])
: httpLink,
});
}
- SSRMultipartLink: A link specifically designed for handling multipart responses in SSR.
- stripDefer: true: Strips interfaces with Directive, when enabled, allows portions of a query to load separately for faster page rendering. Stripping it for SSR simplifies processing, especially since SSR environments may not handle .
If you wish to discuss the topic further, contact me on
SOCIAL SHARE CARD GENERATOR