Swr: Storing initialData in cache

Created on 15 Jul 2020  路  6Comments  路  Source: vercel/swr

Hello,

I have a use-case where I would like to take advantage of the swr built-in cache and store the initialData there.
I found out I can use the cache module e.g.:

import { cache } from 'swr';

cache.set('my-key', initialData);

But I am wondering if there is any other, preferred way of achieving this?

All 6 comments

You can also use the mutate function

Do you see this ever becoming a feature?
e.g.

const { data, error } = useSWR('/api/user', fetcher, { initialData, cacheInitialData: true })

@lukaszromerowicz explanation for the same topic: https://github.com/vercel/swr/pull/388#issuecomment-638085648

I'm dropping my two cents here, what would be an optimal approach to this scenario using Next.js:

export async function getServerSideProps() {
  const user = await fetcher('/me');
  return { props: { user } };
}

function Props(props) {
  const { data } = useSWR('/me', fetcher, { initialData: props.user });

  const handleClick = () => {
    mutate('/me', (cachedUser) => {
      // At the first click of the button, cachedUser will be undefined.
      return { ...cachedUser, name: 'other name' };
    });
  };

  return <button onClick={handleClick}>Change my name {user.name}</button>;
}

At first my solution was to put cache.set('/me', user) inside the getStaticProps function, but I don't know if it will have unintended consequences.

You can also use the mutate function

Would that still work if the key doesn't exist in the cache yet?

@Develliot yes, if it's not in cache it will create it

Was this page helpful?
0 / 5 - 0 ratings