Code Monkey home page Code Monkey logo

solid-sm's Introduction

Solid SM

No non-sense global state management for SolidJS, inspired by Zustand.

import { state } from "solid-sm"

type TaskState = {
    name: string
    done: boolean
    complete(): void
}

type RootState = {
    tasks: TaskState[]
    addTask(name: string): void
}

const createTask = (name: string) => {
    return state<TaskState>((set) => ({
        name,
        done: false,
        complete() {
            set("done", true)
        },
    }))
}

const rootState = state<RootState>((set) => ({
    tasks: [],
    addTask(name) {
        set("tasks", (t) => [...t, createTask(name)])
    },
}))

Features

  • Only one function, for creating a state. That's it.
  • Compatible with SolidJS functions and design patterns.
  • Nestable. Create and update nested states easily.

Motivation

Although Solid provides global state out of the box, dealing with nested states is complex and requires a lot of boilerplate. This module aims to simplify that, reducing the necessary effort to create idiomatic and performant designs.

Usage

Creating a new state

A state is a reactive object with data and actions that can mutate this data. Having actions mixed with data is important because it allows consumers to handle the data without having to known how the data was created. To create a new state, use the state function. It takes setup a callback that returns the initial value.

type CounterState = {
    value: number
}

const counter = state<Counter>(() => ({
    value: 0,
}))

Consuming a state inside a component

Inside components, states behaves as any other reactive object. You can access its properties inside a reactive scope to subscribe it to changes in the property.

function Counter() {
    return <div>Counter: {counter.value}</div>
}

Creating actions to update a state

The state setup callback takes as parameter a set function that can update the state value after it's initialized. With it, you can create actions that will allow the state to be updated by consumers.

type CounterState = {
    value: number
    inc(): void
}

const counter = state<Counter>((set) => ({
    value: 0,
    inc(): {
        // The passed object will be shallowly merged with the current value
        set((s) => ({ value: s.value + 1 }))
        // You can also pass the property that will be updated instead
        set("value", (v) => v + 1)
    }
}))

Using actions in reactive scopes

Solid SM provides a helper function to unwarp actions from the state object. This is useful when using the action directly as a event handler.

type CounterState = {
    value: number
    inc(): void
}

const counter = state<Counter>((set) => ({
    value: 0,
    inc(): {
        set("value", (v) => v + 1)
    }
}))

function Counter() {
    const [inc] = useActions(counter, "inc")

    return (
        <div>
            {counter.value}{" "}
            <button onClick={inc}>Increment</button>
        </div>
    )
}

Creating nested states

Nested states are a way of updating part of a object inside a state without updating the parent state. This simplifies the handling of complex data involving array of objects.

type BookState = {
    title: string
    score: number | null
    setScore(score: number): void
}

type AuthorState = {
    books: BookState[]
    addBook(title: string): void
}

const author = state<AuthorState>((set) => ({
    books: [],
    addBook(title) {
        set("books", (b) => [
            ...b,
            state<BookState>((setBook) => ({
                title,
                score: null,
                setScore(score) {
                    setBook("score", score)
                },
            })),
        ])
    },
}))

solid-sm's People

Contributors

felipesharkao avatar

Stargazers

 avatar

Watchers

 avatar

solid-sm's Issues

State is re-initialized when loaded from SSR

Using Astro's SSR, state is initialized once on the backend, and re-initialized on the front-end, losing any changes to the state during SSR. I need to find a way to bypass the initialization function when loading hydrated function.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.