Unverified Commit 73a05e1e authored by Lenz Weber-Tronic's avatar Lenz Weber-Tronic Committed by GitHub

adopt modern & supported Apollo Client patterns in the with-apollo example (#65316)

#64186 removed the pages router implementation from the `with-apollo`
example and replaced it with an app router implementation.

Unfortunately, it did so in an unsupported way.  
At this point, we can not support any streaming SSR scenario without
additional helper packages - in the case of the app router, it is vital
to use the `@apollo/experimental-nextjs-app-support` package.

This PR switches the example to our officially supported patterns.


<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent b3d90983
......@@ -2,8 +2,6 @@
[Apollo](https://www.apollographql.com/client/) is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run.
In this simple example, we integrate Apollo seamlessly with [Next.js data fetching methods](https://nextjs.org/docs/basic-features/data-fetching) to fetch queries in the server and hydrate them in the browser.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
......
......@@ -7,16 +7,17 @@
"lint": "next lint"
},
"dependencies": {
"@apollo/client": "^3.9.10",
"@apollo/client": "^3.10.1",
"@apollo/experimental-nextjs-app-support": "^0.10.0",
"graphql": "^16.8.1",
"next": "^14.1.4",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"next": "^14.2.3",
"react": "^18.3.0",
"react-dom": "^18.3.0"
},
"devDependencies": {
"@types/node": "^20.12.5",
"@types/react": "^18.2.74",
"@types/react-dom": "^18.2.24",
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"typescript": "^5.4.4"
}
}
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { ApolloClientProvider } from "@/components/ApolloClientProvider";
const inter = Inter({ subsets: ["latin"] });
......@@ -16,7 +17,9 @@ export default function RootLayout({
}>) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
<body className={inter.className}>
<ApolloClientProvider>{children}</ApolloClientProvider>
</body>
</html>
);
}
export default function Loading() {
return <div>Loading...</div>;
}
import { ApolloClientProvider, RepoList } from "@/client-components";
import { FiveRockets } from "@/components/FiveRocketsClient";
import { LatestMissionName } from "@/components/LatestMissionName";
import { Suspense } from "react";
export default async function Home() {
return (
<ApolloClientProvider>
<RepoList />
</ApolloClientProvider>
<>
<article>
<h2>
Latest mission: <LatestMissionName />
</h2>
</article>
<article>
<h2>Five Rockets:</h2>
<Suspense fallback={<div>loading...</div>}>
<FiveRockets />
</Suspense>
</article>
</>
);
}
import { ApolloClient, ApolloProvider, InMemoryCache } from "@apollo/client";
export const client = new ApolloClient({
// URL retrieved from official apollo graphql blog
// See https://www.apollographql.com/blog/using-apollo-client-with-next-js-13-releasing-an-official-library-to-support-the-app-router
uri: "https://main--spacex-l4uc6p.apollographos.net/graphql",
cache: new InMemoryCache(),
});
export function ApolloClientProvider({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return <ApolloProvider client={client}>{children}</ApolloProvider>;
}
"use client";
export { ApolloClientProvider } from "./apollo-client-provider";
export { RepoList } from "./repo-list";
import { gql, useQuery } from "@apollo/client";
const getRepo = gql`
query {
launchLatest {
mission_name
}
}
`;
export function RepoList() {
const { loading, error, data } = useQuery(getRepo);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {JSON.stringify(error)}</p>;
return <div>{data.launchLatest.mission_name}</div>;
}
"use client";
import { HttpLink } from "@apollo/client";
import {
ApolloNextAppProvider,
NextSSRInMemoryCache,
NextSSRApolloClient,
} from "@apollo/experimental-nextjs-app-support/ssr";
function makeClient() {
const httpLink = new HttpLink({
// See more information about this GraphQL endpoint at https://studio.apollographql.com/public/spacex-l4uc6p/variant/main/home
uri: "https://main--spacex-l4uc6p.apollographos.net/graphql",
// you can configure the Next.js fetch cache here if you want to
fetchOptions: { cache: "force-cache" },
// alternatively you can override the default `fetchOptions` on a per query basis
// via the `context` property on the options passed as a second argument
// to an Apollo Client data fetching hook, e.g.:
// ```js
// const { data } = useSuspenseQuery(
// MY_QUERY,
// {
// context: {
// fetchOptions: {
// cache: "no-store"
// }
// }
// }
// );
// ```
});
return new NextSSRApolloClient({
cache: new NextSSRInMemoryCache(),
link: httpLink,
});
}
// you need to create a component to wrap your app in
export function ApolloClientProvider({ children }: React.PropsWithChildren) {
return (
<ApolloNextAppProvider makeClient={makeClient}>
{children}
</ApolloNextAppProvider>
);
}
"use client";
import { TypedDocumentNode, gql, useSuspenseQuery } from "@apollo/client";
export const getRockets: TypedDocumentNode<
{
rockets: Array<{
id: string;
name: string;
}>;
},
{
limit: number;
}
> = gql`
query GetRockets($limit: Int) {
rockets(limit: $limit) {
id
name
}
}
`;
/**
* Example Client Component that uses Apollo Client's `useSuspenseQuery` hook for data fetching.
*/
export function FiveRockets() {
const { data } = useSuspenseQuery(getRockets, {
variables: { limit: 5 },
});
return (
<ul>
{data.rockets.map((rocket) => (
<li key={rocket.id}>{rocket.name}</li>
))}
</ul>
);
}
import { getClient } from "@/lib/ApolloClient";
import { TypedDocumentNode, gql } from "@apollo/client";
export const getLatestMissionName: TypedDocumentNode<{
launchLatest: {
mission_name: string;
};
}> = gql`
query {
launchLatest {
mission_name
}
}
`;
/**
* Example Server Component that uses Apollo Client for data fetching.
*/
export async function LatestMissionName() {
const { data } = await getClient().query({
query: getLatestMissionName,
});
return <div>{data.launchLatest.mission_name}</div>;
}
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
import { registerApolloClient } from "@apollo/experimental-nextjs-app-support/rsc";
export const { getClient } = registerApolloClient(() => {
return new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({
// See more information about this GraphQL endpoint at https://studio.apollographql.com/public/spacex-l4uc6p/variant/main/home
uri: "https://main--spacex-l4uc6p.apollographos.net/graphql",
// you can configure the Next.js fetch cache here if you want to
fetchOptions: { cache: "force-cache" },
// alternatively you can override the default `fetchOptions` on a per query basis
// ```js
// const result = await getClient().query({
// query: MY_QUERY,
// context: {
// fetchOptions: { cache: "force-cache" },
// },
// });
// ```
}),
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment