question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Storing initialData in cache

See original GitHub issue

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?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:3
  • Comments:9 (5 by maintainers)

github_iconTop GitHub Comments

5reactions
ties-vcommented, Jan 25, 2021

I have the same issue as @zomars and use this workaround for now. Maybe it is helpful for others.

import { useEffect, useRef } from 'react';
import _useSwr, {cache} from 'swr';
import { ConfigInterface, keyInterface, fetcherFn, responseInterface } from 'swr/dist/types';

/**
 * Patched version of SWR to work around the fact that initial data is not inserted to the cache.
 *
 * This is an issue when using useSWR with initialData and then calling mutate with a function that
 * expects the current value. Before the data is revalidated, the function passed to mutate will
 * receive undefined.
 *
 * Based on:
 * @see https://github.com/vercel/swr/issues/284#issuecomment-706094532
 */
const useSwr = <Data = unknown, Error = unknown>(
    key: keyInterface,
    fn?: fetcherFn<Data>,
    config?: ConfigInterface<Data, Error>
): responseInterface<Data, Error> => {
    const hasMounted = useRef(false);

    if (config?.initialData) {
        const [k, ,] = cache.serializeKey(key)
        // Set initial data as cache value if:
        // initialData is set
        // it is the first render
        // and the cache value for this key is undefined
        if (!hasMounted.current && cache.get(k) === undefined) {
            cache.set(k, config?.initialData)
        }
    }

    useEffect(() => {
        hasMounted.current = true;
    }, []);

    return _useSwr<Data, Error>(key, fn, config);
};

export default useSwr;

It basically sets the value of initialData into the cache on the first render, if the cache is empty for this key.

3reactions
lukaszromerowiczcommented, Jul 16, 2020

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

const { data, error } = useSWR('/api/user', fetcher, { initialData, cacheInitialData: true })
Read more comments on GitHub >

github_iconTop Results From Across the Web

Initial Query Data | TanStack Query Docs
There are many ways to supply initial data for a query to the cache before ... once when the query is initialized, saving...
Read more >
How to fix SWR to work correctly with initialData or fallbackData
SWR is a lightweight library that makes remote data fetching, caching or refetching data easier, exposing this via a React hook. The basic...
Read more >
Interacting with cached data - Apollo GraphQL Docs
The readFragment method enables you to read data from any normalized cache object that was stored as part of any query result. Unlike...
Read more >
Cached data or Using storage in flutter? - Stack Overflow
I have a backend server with graphql. And on flutter startup, I call query to backend for initial data. This initial data needs...
Read more >
Storing local data with Apollo Client | by Eugenia Zigisova
Setting initial data. To make Graphql query work, Apollo Cache needs to expose it. To set local state fields to the cache typePolicies...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found