@fromscratch/store
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

@fromscratch/store

yarn add @fromscratch/store

Usage

Example with react

import React, { Component } from "react";
import Store from "@fromscratch/store";

const store = new Store();

// Some value update from anywhere in the codebase
store.set('someValue', {
  someList: [...]
})

export default class App extends Component {
  componentDidMount() {
    this.unsubscribe = store.subscribe("someValue", this.handleUpdate);
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  handleUpdate = data => {
    this.setState({ data });
  };

  deleteItem = index => () => {
    const currentValue = store.get("someValue", []);
    store.set("someValue", [
      ...currentValue.slice(0, index),
      ...currentValue.slice(index + 1)
    ]);
  };

  deleteAll = () => {
    store.delete("someValue");
  };

  render() {
    const { data } = this.state;
    return (
      <>
        <button onClick={this.deleteAll}>Remove all</button>
        <ul>
          {data.someList.map((item, index) => (
            <li>
              {item.label} <button onClick={this.deleteItem(index)}>x</button>
            </li>
          ))}
        </ul>
      </>
    );
  }
}

API

class Store {
  get: (key: string, defaultValue?: any) => any;
  set: (key: string, value: any) => void;
  delete: (key: string) => void;
  subscribe: (key: string, fn: (value: any) => void) => () => void;
}

Dependents (1)

Package Sidebar

Install

npm i @fromscratch/store

Weekly Downloads

0

Version

1.0.2

License

MIT

Unpacked Size

3.41 kB

Total Files

4

Last publish

Collaborators

  • didierfranc