SoulCache

Quick Start

Get up and running with SoulCache in 5 minutes

Quick Start

This guide will get you up and running with SoulCache in under 5 minutes.

Install SoulCache

npm install @soulcache/core

Create a Query Client

import { QueryClient } from '@soulcache/core';
 
const client = new QueryClient({
  defaultOptions: {
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 30 * 60 * 1000, // 30 minutes
  },
});

Fetch Data

// Fetch with automatic caching
const data = await client.fetchQuery({
  queryKey: ['users'],
  queryFn: () => fetch('/api/users').then(r => r.json()),
});

Subscribe to Changes

// Subscribe to query updates
const unsubscribe = client.subscribe(['users'], (snapshot) => {
  console.log('Data updated:', snapshot.data);
  console.log('Status:', snapshot.status);
});

Update Cache

// Optimistically update cache
client.setQueryData(['users'], (old) => [...old, newUser]);
 
// Invalidate and refetch
await client.invalidateQueries(['users']);

Cleanup

// Cleanup when done
client.destroy();

Complete Example

Here's a complete example putting it all together:

import { QueryClient } from '@soulcache/core';
 
async function main() {
  // Create client
  const client = new QueryClient();
 
  // Define a query
  const users = await client.fetchQuery({
    queryKey: ['users'],
    queryFn: async () => {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      return response.json();
    },
  });
 
  console.log('Users:', users);
 
  // Subscribe to changes
  const unsubscribe = client.subscribe(['users'], (snapshot) => {
    console.log('Update received:', snapshot.data);
  });
 
  // Update cache
  client.setQueryData(['users'], (old) => [
    ...old,
    { id: 4, name: 'New User' },
  ]);
 
  // Cleanup
  unsubscribe();
  client.destroy();
}
 
main();

Next Steps

On this page