Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

localstoragecollectionoptions.md

195 lines3.6 KB

Function: localStorageCollectionOptions()

function localStorageCollectionOptions<TExplicit, TSchema, TFallback>(config): object

Defined in: packages/db/src/local-storage.ts:205

Creates localStorage collection options for use with a standard Collection

This function creates a collection that persists data to localStorage/sessionStorage and synchronizes changes across browser tabs using storage events.

Type Parameters

• TExplicit = unknown

The explicit type of items in the collection (highest priority)

• TSchema extends StandardSchemaV1<unknown, unknown> = never

The schema type for validation and type inference (second priority)

• TFallback extends object = Record<string, unknown>

The fallback type if no explicit or schema type is provided

Parameters

config

LocalStorageCollectionConfig<TExplicit, TSchema, TFallback>

Configuration options for the localStorage collection

Returns

object

Collection options with utilities including clearStorage and getStorageSize

getKey()

getKey: (item) => string | number;

Parameters

item

ResolveType

Returns

string | number

id

id: string = collectionId;

onDelete()

onDelete: (params) => Promise<any> = wrappedOnDelete;

Parameters

params

DeleteMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>>

Returns

Promise<any>

onInsert()

onInsert: (params) => Promise<any> = wrappedOnInsert;

Parameters

params

InsertMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>>

Returns

Promise<any>

onUpdate()

onUpdate: (params) => Promise<any> = wrappedOnUpdate;

Parameters

params

UpdateMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>>

Returns

Promise<any>

schema?

optional schema: TSchema;

sync

sync: SyncConfig<ResolveType<TExplicit, TSchema, TFallback>, string | number> & object;

Type declaration

manualTrigger()?
optional manualTrigger: () => void;
Returns

void

utils

utils: object;

utils.clearStorage

clearStorage: ClearStorageFn;

utils.getStorageSize

getStorageSize: GetStorageSizeFn;

Examples

// Basic localStorage collection
const collection = createCollection(
  localStorageCollectionOptions({
    storageKey: 'todos',
    getKey: (item) => item.id,
  })
)
// localStorage collection with custom storage
const collection = createCollection(
  localStorageCollectionOptions({
    storageKey: 'todos',
    storage: window.sessionStorage, // Use sessionStorage instead
    getKey: (item) => item.id,
  })
)
// localStorage collection with mutation handlers
const collection = createCollection(
  localStorageCollectionOptions({
    storageKey: 'todos',
    getKey: (item) => item.id,
    onInsert: async ({ transaction }) => {
      console.log('Item inserted:', transaction.mutations[0].modified)
    },
  })
)