Peter Kellner
Peter Kellner

Reputation: 15498

Expecting SWR library to return cached data but not happening

I'm using the Vercel SWR hook usrSWR and I'm expecting that I can get the data stored in cache in some faraway component rather than having to use context or some other global state manager.

Specifically, I am setting the cache data in IndexPage with initialData, I can see that the data returned is correct, but when I try and retrieve the same data from OtherComponent data is returned as undefined.

I have the code in codesandbox here: https://codesandbox.io/s/useswr-global-cache-example-forked-8qxh7?file=/pages/index.js

import useSWR from "swr";

export default function IndexPage({ speakersData }) {
  const { data } = useSWR("globalState", { initialData: speakersData });

  return (
    <div>
      This is the Index Page <br />
      data: {JSON.stringify(data)}
      <br />
      <OtherComponent></OtherComponent>
    </div>
  );
}

function OtherComponent() {
  const { data } = useSWR("globalState");
  return <div>I'm thinking this should get my global cache but it does not {JSON.stringify(data)}</div>;
}

export async function getServerSideProps() {
  const speakersData = [{ id: 101 }, { id: 102 }];
  return { props: { speakersData: speakersData } };
}

Upvotes: 3

Views: 2384

Answers (1)

juliomalves
juliomalves

Reputation: 50338

I'm afraid you'll need to pass the data down to the child component (or using React Context) to populate its initialData as well, otherwise it won't have any data initially - data passed to initialData isn't stored in cache.

Also, unless you provide the fetcher method globally, you should pass it to the useSWR calls.

import useSWR from "swr";

const getData = async () => {
  return [{ id: 101 }, { id: 102 }];
};

export default function IndexPage({ speakersData }) {
    const { data } = useSWR("globalState", getData, { initialData: speakersData });

    return (
        <div>
            This is the Index Page <br />
            data: {JSON.stringify(data)}
            <br />
            <OtherComponent speakersData={speakersData}></OtherComponent>
        </div>
    );
}

function OtherComponent({ speakersData }) {
    const { data } = useSWR("globalState", getData, { initialData: speakersData });
    return <div>I'm thinking this should get my global cache but it does not {JSON.stringify(data)}</div>;
}

export async function getServerSideProps() {
    const speakersData = await getData();
    return { props: { speakersData } };
}

Upvotes: 1

Related Questions