Simple store for Deno Fresh, to pass state between islands

Overview

Fresh Store

Build Passing CodeQL

A minimal store for Fresh, to allow communication between islands. It attach stores to the window component. It uses "pointers" or "keys" to associate stores. A pointer can either be provided, or auto-generated.

Usage

Creating a store.

const ptr = useStore("Initial Value", { onChange: (state) => console.log(state) });

console.log(Stores.get<string>(ptr)?.state);
Stores.get<string>(ptr)?.set("Modified Value");
Output:
Initial Value
Modified Value

Creating a store and providing a pointer.

const pointer = Store.newPointer();
useStore(
    "Initial Value", 
    {
        pointer: pointer,
        onChange: (newState) => console.log(`New value: ${newState}`)
    },
);

console.log(Stores.get<string>(ptr)?.state);
Stores.get<string>(ptr)?.set("Modified Value");
Output:
Initial Value
New value: Modified Value

Creating a new Observer

const storePtr = useStore("New Store");

class ConcreteObserver implements Observer<T> {
    public update(subject: Store<T>): void {
        console.log("The store was updated, new state: ", subject.state);
    }
}

Stores.get(storePtr)?.attach(new ConcreteObserver());

Example usage in components

// ./islands/componentA.tsx

/** @jsx h */
import { h } from "preact";
import { Stores, useStore, type Pointer } from "@store";

interface CompAProps {
    storePtr: Pointer;
}

export default function ComponentA(props: CompAProps) {
    useStore(0, { pointer: props.storePtr });

    const increment = () => 
        Stores
            .get<number>(props.storePtr)
            ?.set((state) => state + 1);
    
    const decrement = () =>
       Stores
            .get<number>(props.storePtr)
            ?.set((state) => state - 1);
    
    return (
        <div>
            <button onClick={decrement}>-1</button>
            <button onClick={increment}>+1</button>
        </div>
    );
}
// ./islands/componentB.tsx

/** @jsx h */
import { h } from "preact";
import { useState } from "preact/hooks";

import { useStore, type Pointer } from "@store";

interface CompBProps {
    storePtr: Pointer;
}

export default function ComponentB(props: CompBProps) {
    const [counter, setCounter] = useState(0);
    useStore(counter, {
        pointer: props.storePtr,
        onChange: (newState) => setCounter(newState),
    });

    return <p>Counter: {counter}</p>;
}
// ./routes/index.tsx

/** @jsx h */
import { h } from "preact";

import { Store } from "@store";

import ComponentA from "@islands/componentA.tsx";
import ComponentB from "@islands/componentB.tsx";

export default function Index() {
    const storePtr = Store.newPointer();

    return (
        <div>
            <ComponentA storePtr={storePtr} />
            <ComponentB storePtr={storePtr} />
        </div>
    );
}
You might also like...

Timers for Lost Ark bosses, islands, events, wandering merchants and more! Never miss an event again.

Timers for Lost Ark bosses, islands, events, wandering merchants and more! Never miss an event again.

Timers for Lost Ark bosses, islands, events, wandering merchants and more! Never miss an event again. LostArkTimer.app Website Website Features Event

Oct 17, 2022

Privacy Pass: a privacy-enhancing protocol and browser extension.

Privacy Pass Extension The Privacy Pass protocol is now being standardised by the privacypass IETF working group. All contributions are welcome! See t

Jan 7, 2023

JavaScript micro-library: pass in an element and a callback and this will trigger when you click anywhere other than the element

Add a click listener to fire a callback for everywhere on the window except your chosen element. Installation run npm install @lukeboyle/when-clicked-

May 13, 2021

📝 Vite & Mdx powered static site generator.Base on islands architecture

Island.js A static site generator for the modern web.It has following features: 🚀 Base on Vite, it has great development experience. 🏝️ Islands arch

Dec 25, 2022

Differences between Node + Koa and Deno + Oak

Node + Koa VS Deno + Oak Differences between Node + Koa and Deno + Oak About This is a project that aims to observe the differences between a simple R

Jun 28, 2022

This is a simple boilerplate for a Deno website, deployed with Deno Deploy.

Simple Deno Website Boilerplate This is a simple website boilerplate built using Deno and deployed using Deno Deploy. Demo at simple-deno-website-boil

Dec 3, 2022

A fresh look for the Hackage. Follow us: https://twitter.com/HackageUI

A fresh look for the Hackage. Follow us: https://twitter.com/HackageUI

Hackage UI Fresh look for the https://hackage.haskell.org/. Work in progress. Search Search on Hoogle. Search on Hackage. Full-text search integration

Dec 28, 2022

Fresh SQLite example on Fly.io.

fresh-sqlite-example Fresh example with SQLite and kysely query builder. See running example on Fly.io. Prerequisites Deno v1.23 or higher SQLite Opti

Nov 25, 2022

Easy server-side and client-side validation for FormData, URLSearchParams and JSON data in your Fresh app 🍋

Fresh Validation 🍋     Easily validate FormData, URLSearchParams and JSON data in your Fresh app server-side or client-side! Validation Fresh Validat

Dec 23, 2022
Releases(v1.0.2)
Dead simple cookie-based session for Deno Fresh.

Fresh Session ?? Dead simple cookie-based session for Deno Fresh. Get started Fresh Session comes with a simple middleware to add at the root of your

Steven Yung 38 Jan 5, 2023
A fresh (deno) app

Welcome to fresh-deno-app ?? A fresh (deno) app ?? Homepage ✨ Demo Prerequisites Deno version 1.22.3 or higher installed. - A modern runtime for JavaS

Dung Duc Huynh (Kaka) 4 Oct 17, 2022
The fastest way ⚡️ to create sitemap in your Deno Fresh project 🍋

Fresh SEO ??     Quickly creating sitemaps for your Deno Fresh project. Getting Started Run the setup at the root of your project. deno run

Steven Yung 34 Dec 19, 2022
A minimal blog template using the Fresh framework for Deno.

Fresh Blog This is a minimal blog template using the awesome framework Fresh from Deno. Usage Start the project: deno task start This will watch the

Little Sticks 21 Dec 16, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Opinionated collection of TypeScript definitions and utilities for Deno and Deno Deploy. With complete types for Deno/NPM/TS config files, constructed from official JSON schemas.

Schemas Note: You can also import any type from the default module, ./mod.ts deno.json import { type DenoJson } from "https://deno.land/x/[email protected]

deno911 2 Oct 12, 2022
Pass trust from a front-end Algorand WalletConnect session, to a back-end web service

AlgoAuth Authenticate to a website using only your Algorand wallet Pass trust from a front-end Algorand WalletConnect session, to a back-end web servi

Nullable Labs 16 Dec 15, 2022