Skip to main content
Module

x/fresh_store/mod.ts>useStore

Simple store for Deno Fresh, to pass state between islands
Go to Latest
function useStore
import { useStore } from "https://deno.land/x/fresh_store@v1.0.1/mod.ts";

Convenience function to create a store. Multiple options can be provided, see StoreOptions.

Unless the override option is set to true, this function will not override an existing store, it is therefore safe to use to make sure a store is defined in multiple components.

If no pointer is provided, a pointer will be assigned and returned.

Example

// 1. Creating a store without any options
const store1Ptr = useStore(0);
console.log(Stores.get<number>(store1Ptr).state); // Output: 0

// 2. Creating a store with options
const store2Ptr = crypto.randomUUID();
useStore(0, { pointer: store2Ptr, onChange: (state) => console.log(state), });

console.log(Stores.get<number>(store2Ptr).state); // Ouput: 0
Stores.get<number>(store2Ptr).set((prevState) => prevState + 1); // Ouput: 1

Parameters

state: T

The initial state. If the store already exists, it will not overwrite the state unless the override option is set to true.

optional
options: StoreOptions<T>

Returns

The Pointer to the location of the store.