DEV Community

张一凡
张一凡

Posted on

Getting started with easy-model (quick start guide)

TL;DR

  • Install and write a model class.
  • Use useModel to create/subscribe in React.
  • Use provide for shared instances.

1) Install

pnpm add @e7w/easy-model
Enter fullscreen mode Exit fullscreen mode

2) Create a model

class TodoModel {
  items: string[] = [];
  add(text: string) {
    this.items.push(text);
  }
  remove(index: number) {
    this.items.splice(index, 1);
  }
}
Enter fullscreen mode Exit fullscreen mode

3) Use it in a component

import { useModel } from "easy-model";

function TodoList() {
  const todo = useModel(TodoModel, []);
  return (
    <div>
      <button onClick={() => todo.add("new item")}>Add</button>
      <ul>
        {todo.items.map((it, i) => (
          <li key={i} onClick={() => todo.remove(i)}>
            {it}
          </li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This is the core workflow: model-first design with minimal React glue. If you already model business logic with classes, easy-model makes state feel natural.

GitHub: easy-model

npm: @e7w/easy-model

Top comments (0)