JSPM

  • Created
  • Published
  • Downloads 19
  • Score
    100M100P100Q45114F
  • License BSD-2-Clause

Package Exports

  • @tty-pt/sub
  • @tty-pt/sub/dist/main.amd.js
  • @tty-pt/sub/dist/main.d.ts
  • @tty-pt/sub/dist/main.js
  • @tty-pt/sub/dist/main.js.map
  • @tty-pt/sub/package.json
  • @tty-pt/sub/src/main.d.ts
  • @tty-pt/sub/src/main.tsx

Readme

@tty-pt/sub - Quantum subscription system

This helps you have state outside of your components, like Redux, but simpler.

Take this example:

import React, { useRef } from "react";
import { Sub, reflect } from "@tty-pt/sub";

class TodoSub extends Sub {
    @reflect()
    add(text) {
        return { ...this.get(), [text]: text };
    }
}

export
const todoSub = new TodoSub();

export default
function Todos(props) {
    const todos = todoSub.use();
    const ref = useRef();

    return <div>{
        <div key="header">
            <input ref={ref}></input>
            <button onClick={() => {
                todoSub.add(ref.current.value);
                ref.current.value = "";
            }}>add</button>
        </div>
        Object.entries(todos).map(([key, value]) => (
            <div key={key}>{value}</div>
        ));
    }</div>
}

This will display a todo list. When you click the button, it will add the text from an input into the todo list.

You could do this with state inside of your component. But then, it would get re-set if the Todos component unmounts for some reason.

Meaning you would lose your todos list if the component re-mounted for some reason.

This way. You get to keep your todos, indepedently of the state of the component.

If it disappears and then reappears, it's state is kept.

What does it mean to have state outside components like this? For one you could trigger state changes in this component from afar without having to pass down props in a confusing way. You'd just have to call "todoSub.add". Or subscribe to its value if you were interested.

Now imagine you added this line to that file:

window.todo = todoSub;

Well, now you can trigger state changes in the todos component from devTools. Nice.

I've left a few tools there so you can easily debug your methods, setters, getters etc.

You'd just have to do stuff like:

todo.debug = ["emit add"];

To see when "add" gets invoked, and what it returns.