From 10e375f5397fe10538a3ac9909768aa02f719798 Mon Sep 17 00:00:00 2001 From: Shaw Date: Thu, 5 Aug 2021 11:37:22 -0500 Subject: [PATCH] Attribution and refetching example --- data/apollo.js | 2 +- pages/index.js | 57 ++++++++++++++++++++++++++++++++++++++------------ 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/data/apollo.js b/data/apollo.js index ffd7a21..2aa008d 100644 --- a/data/apollo.js +++ b/data/apollo.js @@ -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 || {}) }); diff --git a/pages/index.js b/pages/index.js index 27fcfbd..ffa8c84 100644 --- a/pages/index.js +++ b/pages/index.js @@ -1,4 +1,4 @@ -import { useQuery, gql } from "@apollo/client"; +import { useQuery, gql, NetworkStatus } from "@apollo/client"; import React, { useEffect, useState } from "react"; const QUERY = gql` @@ -6,30 +6,61 @@ const QUERY = gql` 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
Loading...
; - } + if (loading) return "Loading..."; return (
-

Apollo GraphQL Server-Side Rendering

+

Next.js Server-Side Rendering with Apollo GraphQL

+

+ + 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. + +

+ +

+ Data provided by{" "} + + https://api.graphql.jobs/ + + . +

+

- {cached ? "Data was cached from SSR" : "Data was not cached from SSR"} + This page's data was fetched on the{" "} + {cached ? "Next.js server" : "client"}.
+ Network Status: {networkStatus}{" "} +

- {list.map((item) => { + {[...data?.jobs].map((item) => { return (
    {Object.entries(item).map(([key, value]) => {