All files / react-classic/src/storage session.ts

100% Statements 12/12
100% Branches 2/2
100% Functions 1/1
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30    1x 1x                               1x 4x 4x 4x 4x 4x 4x 4x 4x 4x  
import type { LinkableSchema, ObjLike, StateOptions } from '@anchorlib/core';
import type { ConstantState } from '../index.js';
import { useConstant } from '../index.js';
import { session } from '@anchorlib/storage';
 
/**
 * A React hook that provides session storage functionality with state management.
 *
 * This hook creates a session storage entry with the given name and initial value,
 * and returns a tuple containing the current value, the state object, and a setter function.
 *
 * @template T - The type of the initial value object
 * @template S - The schema type for linkable data structures
 *
 * @param name - The unique identifier for the session storage entry
 * @param init - The initial value to store in session storage
 * @param options - Optional configuration for state management
 * @return {ConstantState<T>} - A constant state object containing the stored value and its associated reference
 */
export function useSession<T extends ObjLike, S extends LinkableSchema = LinkableSchema>(
  name: string,
  init: T,
  options?: StateOptions<S>
): ConstantState<T> {
  const [state] = useConstant(() => {
    return session(name, init, options);
  }, [name, init, options]);
  return [state.value, state];
}