Skip to content

Commit

Permalink
Attribution and refetching example
Browse files Browse the repository at this point in the history
  • Loading branch information
shshaw committed Aug 5, 2021
1 parent c6cfece commit 10e375f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 14 deletions.
2 changes: 1 addition & 1 deletion data/apollo.js
Expand Up @@ -11,7 +11,7 @@ let CLIENT;
export function getApolloClient() {
if (!CLIENT) {
CLIENT = new ApolloClient({
ssrMode: true,
ssrMode: isServer,
uri: "https://api.graphql.jobs/",
cache: new InMemoryCache().restore(windowApolloState || {})
});
Expand Down
57 changes: 44 additions & 13 deletions pages/index.js
@@ -1,35 +1,66 @@
import { useQuery, gql } from "@apollo/client";
import { useQuery, gql, NetworkStatus } from "@apollo/client";
import React, { useEffect, useState } from "react";

const QUERY = gql`
query Jobs {
jobs {
id
title
locationNames
}
}
`;

export default function IndexPage() {
const { data, loading, error } = useQuery(QUERY);
const list = data?.jobs || [];
console.log({ loading, data, error });
const { data, loading, networkStatus, error, refetch } = useQuery(QUERY, {
notifyOnNetworkStatusChange: true
});

console.log({ loading, data, error, refetch });

// On page load, the `networkStatus` should be NetworkStatus.ready ( `7` ) if the data is in the cache, and the page should not need to re-render.
const [cached, setCached] = useState(true);
useEffect(() => {
if (loading) setCached(false);
}, [loading]);
if (networkStatus !== NetworkStatus.ready) setCached(false);
}, [networkStatus]);

if (loading) {
return <div>Loading...</div>;
}
if (loading) return "Loading...";

return (
<div>
<h1>Apollo GraphQL Server-Side Rendering</h1>
<h1>Next.js Server-Side Rendering with Apollo GraphQL</h1>
<p>
<strong>
A simple approach to server-side rendering in Next.js with Apollo
GraphQL, featuring no duplicate queries or complicated client/server
logic, cache hydration and live queries for the client.
</strong>
</p>

<p>
Data provided by{" "}
<a
href="https://api.graphql.jobs/"
target="_blank"
rel="noopener noreferrer"
>
https://api.graphql.jobs/
</a>
.
</p>

<p>
{cached ? "Data was cached from SSR" : "Data was not cached from SSR"}
This page's data was fetched on the{" "}
<strong>{cached ? "Next.js server" : "client"}</strong>.<br />
Network Status: <strong>{networkStatus}</strong>{" "}
<button
onClick={() =>
refetch({
fetchPolicy: "network-only"
})
}
>
Refetch
</button>
</p>

<div
Expand All @@ -38,7 +69,7 @@ export default function IndexPage() {
grid: "auto / repeat(auto-fit, minmax(15em,1fr))"
}}
>
{list.map((item) => {
{[...data?.jobs].map((item) => {
return (
<ul key={item.id}>
{Object.entries(item).map(([key, value]) => {
Expand Down

0 comments on commit 10e375f

Please sign in to comment.