javascriptlocal-storagetanstackreact-querytanstack

TanStack query local storage full


We are using TanStack query (Vue) for storing a lot of states in the local storage.

But what happens if the local storage is full? Will it just discard the oldest query if we store a new query?


Solution

  • So when your localStorage is full, TanStack Query does not automatically discard old queries to make space for new ones. Instead, attempting to write to a full localStorage will throw a QuotaExceededError, causing the save operation to fail.

    You can catch that error by simply limiting the amount of data stored by configuring TanStack Query's cache settings.

    import { QueryClient } from '@tanstack/vue-query';
    import { persistQueryClient } from '@tanstack/query-persist-client-core';
    import { createSyncStoragePersister } from '@tanstack/query-persist-client-core';
    
    const queryClient = new QueryClient({
      defaultOptions: {
        queries: {
          gcTime: 1000 * 60 * 60 * 24, // 24 hours cache time
          staleTime: 1000 * 60 * 5, // 5 minutes stale time
        },
      },
    });
    
    const persister = createSyncStoragePersister({
      storage: localStorage,
      key: 'tanstack-query',
      maxAge: 1000 * 60 * 60 * 24, // Persist queries for 24 hours
      serialize: (data) => JSON.stringify(data, null, 0),
      deserialize: (data) => JSON.parse(data),
    
      // Only persist specific queries to save space
      filter: (query) => query.meta?.persist === true,
    });
    
    persistQueryClient({
      queryClient,
      persister,
    });
    

    Hope this helps you bud! Happy Building!