CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vueuse--integrations

Vue.js composition API wrappers for popular utility libraries enabling seamless integration of third-party tools

Pending
Overview
Eval results
Files

storage-state.mddocs/

Storage and State Management

Persistent storage solutions using cookies, IndexedDB, and JWT token handling for maintaining application state.

Capabilities

useCookies

Reactive cookie management with automatic reactivity and SSR support.

/**
 * Reactive cookie management with automatic reactivity
 * @param dependencies - Array of cookie names to watch for changes
 * @param options - Configuration options
 * @param cookies - Custom cookie instance (for SSR)
 * @returns Cookie management interface
 */
function useCookies(
  dependencies?: string[] | null,
  options?: {
    doNotParse?: boolean;
    autoUpdateDependencies?: boolean;
  },
  cookies?: Cookie
): {
  /** Get a cookie value by name */
  get: <T = any>(...args: Parameters<Cookie['get']>) => T;
  /** Get all cookies as an object */
  getAll: <T = any>(...args: Parameters<Cookie['getAll']>) => T;
  /** Set a cookie value */
  set: (...args: Parameters<Cookie['set']>) => void;
  /** Remove a cookie */
  remove: (...args: Parameters<Cookie['remove']>) => void;
  /** Add change listener */
  addChangeListener: (...args: Parameters<Cookie['addChangeListener']>) => void;
  /** Remove change listener */
  removeChangeListener: (...args: Parameters<Cookie['removeChangeListener']>) => void;
};

/**
 * Create a cookie factory for SSR environments
 * @param req - HTTP request object (for SSR)
 * @returns useCookies factory function
 */
function createCookies(req?: IncomingMessage): (
  dependencies?: string[] | null,
  options?: { doNotParse?: boolean; autoUpdateDependencies?: boolean }
) => ReturnType<typeof useCookies>;

Usage Examples:

import { useCookies } from "@vueuse/integrations/useCookies";

// Basic cookie management
const cookies = useCookies(['user-preferences', 'auth-token']);

// Set cookies
cookies.set('theme', 'dark', { path: '/' });
cookies.set('user-id', '12345', { 
  expires: new Date(Date.now() + 86400000) // 1 day
});

// Get cookies
const theme = cookies.get('theme'); // 'dark'
const allCookies = cookies.getAll();

// Remove cookies
cookies.remove('old-setting');

// Auto-update dependencies
const cookies = useCookies(null, { 
  autoUpdateDependencies: true 
});

// SSR usage
import { createCookies } from "@vueuse/integrations/useCookies";

// In your server-side code
const cookieFactory = createCookies(req);
const cookies = cookieFactory(['session']);

useIDBKeyval

Reactive IndexedDB storage with automatic persistence and type safety.

/**
 * Reactive IndexedDB storage with automatic persistence
 * @param key - IndexedDB key for storage
 * @param initialValue - Initial value if key doesn't exist
 * @param options - Configuration options
 * @returns Reactive storage interface
 */
function useIDBKeyval<T>(
  key: IDBValidKey,
  initialValue: MaybeRefOrGetter<T>,
  options?: UseIDBOptions<T>
): UseIDBKeyvalReturn<T>;

interface UseIDBKeyvalReturn<T> {
  /** Reactive data value with automatic persistence */
  data: RemovableRef<T>;
  /** Whether initial load from IndexedDB is complete */
  isFinished: ShallowRef<boolean>;
  /** Manually set the value */
  set: (value: T) => Promise<void>;
}

interface UseIDBOptions<T> extends ConfigurableFlush {
  /** Deep watch the data for changes */
  deep?: boolean; // default: true
  /** Error callback function */
  onError?: (error: unknown) => void;
  /** Use shallow ref for data */
  shallow?: boolean; // default: false
  /** Write initial/default values to storage */
  writeDefaults?: boolean; // default: true
  /** Custom serializer for complex data types */
  serializer?: Serializer<T>;
}

interface Serializer<T> {
  /** Deserialize data from storage */
  read: (raw: unknown) => T;
  /** Serialize data for storage */
  write: (value: T) => unknown;
}

interface RemovableRef<T> extends Ref<T> {
  /** Remove the value from storage and reset to initial */
  $remove: () => void;
}

Usage Examples:

import { useIDBKeyval } from "@vueuse/integrations/useIDBKeyval";

// Basic usage
const { data, isFinished } = useIDBKeyval('user-settings', {
  theme: 'light',
  language: 'en'
});

// Wait for initial load
watchEffect(() => {
  if (isFinished.value) {
    console.log('Settings loaded:', data.value);
  }
});

// Update data (automatically persisted)
data.value.theme = 'dark';

// Remove from storage
data.$remove();

// With custom serializer
const { data } = useIDBKeyval('complex-data', new Map(), {
  serializer: {
    read: (value) => new Map(value as any),
    write: (value) => Array.from(value.entries())
  }
});

// Error handling
const { data } = useIDBKeyval('my-key', null, {
  onError: (error) => {
    console.error('IndexedDB error:', error);
  }
});

useJwt

JWT token decoding with reactive payload and header extraction.

/**
 * JWT token decoding with reactive payload and header extraction
 * @param encodedJwt - Encoded JWT token string
 * @param options - Configuration options
 * @returns Decoded JWT header and payload
 */
function useJwt<
  Payload extends object = JwtPayload,
  Header extends object = JwtHeader,
  Fallback = null
>(
  encodedJwt: MaybeRefOrGetter<string>,
  options?: UseJwtOptions<Fallback>
): UseJwtReturn<Payload, Header, Fallback>;

interface UseJwtReturn<Payload, Header, Fallback> {
  /** Reactive JWT header */
  header: ComputedRef<Header | Fallback>;
  /** Reactive JWT payload */
  payload: ComputedRef<Payload | Fallback>;
}

interface UseJwtOptions<Fallback> {
  /** Fallback value when decoding fails */
  fallbackValue?: Fallback; // default: null
  /** Error callback function */
  onError?: (error: unknown) => void;
}

// Standard JWT interfaces
interface JwtPayload {
  iss?: string;
  sub?: string;
  aud?: string | string[];
  exp?: number;
  nbf?: number;
  iat?: number;
  jti?: string;
  [key: string]: any;
}

interface JwtHeader {
  typ?: string;
  alg?: string;
  [key: string]: any;
}

Usage Examples:

import { useJwt } from "@vueuse/integrations/useJwt";
import { ref } from 'vue';

// Basic JWT decoding
const token = ref('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');
const { header, payload } = useJwt(token);

// Access token data
console.log('Algorithm:', header.value?.alg);
console.log('User ID:', payload.value?.sub);
console.log('Expires:', new Date((payload.value?.exp || 0) * 1000));

// Custom payload type
interface CustomPayload {
  userId: string;
  role: string;
  permissions: string[];
}

const { payload } = useJwt<CustomPayload>(token);
console.log('Role:', payload.value?.role);

// With fallback value and error handling
const { header, payload } = useJwt(token, {
  fallbackValue: { error: 'Invalid token' },
  onError: (error) => {
    console.error('JWT decode error:', error);
  }
});

// Check token expiration
const isTokenExpired = computed(() => {
  const exp = payload.value?.exp;
  return exp ? Date.now() >= exp * 1000 : true;
});

Install with Tessl CLI

npx tessl i tessl/npm-vueuse--integrations

docs

form-validation.md

http-client.md

index.md

search-data.md

storage-state.md

ui-interactions.md

visual-effects.md

tile.json