Skip to content

Latest commit

 

History

History
144 lines (102 loc) · 3.19 KB

README.md

File metadata and controls

144 lines (102 loc) · 3.19 KB

Ya Signals

React application architecture on MobX.

npm version npm bundle size

Installation

npm install ya-signals

Logic

On demand services

Edit example in Codesandbox

import { service, makeObservable, observable } from "ya-signals";

// AppService.ts

class AppService {
  public lang: string;

  constructor() {
    this.lang = "ru";

    makeObservable(this, {
      lang: observable.ref, // immutable value
    });
  }
}

// Only Proxy for create class on demand in future
export const appService = service(AppService);

If you run appService.lang in your code anywhere it's get app property for on demand created service

import { observer } from "ya-signals";
import { appService } from "./AppService.ts"

// App.tsx

export const App = observer(() => {
  return (
    <div className="App">
      <h1>App lang {appService.lang}</h1>
    </div>
  );
});

In rare cases when it's necessary to initialize a service without invoking any method.

service.instantiate(appService);

In rare case when it's necessary to destroy a service manually.

service.destroy(appService);

Describe component logic in OOP-style

import { hook, un } from "ya-signals";

class RecipeForm {
  constructor() {
    un(() => {
      // destroy
    })
  }
}

export const useRecipeForm = hook(RecipeForm)

// Somewhere in React component
const form = useRecipeForm()

And it can be with params of course

Edit example in Codesandbox

import { hook, type SignalReadonly } from "ya-signals";

// Can be object struct with named fields
type Params = {
  count: number;
  text: string;
};

class LocalLogic {
  constructor($params: SignalReadonly<Params>) {
    console.log("constructor with params", $params.value);

    $params.subscribe((params) => {
      console.log("updated params", params);
    });
  }
}

const useLocalLogic = hook(LocalLogic);

The signal documentation see here.

And using it somewhere inside React component function

import { useRecipeForm } from './recipe-form.ts';

function Form() {
  const [count, setCount] = useState(() => 1);
  const [text, setText] = useState(() => "Hello");
  const logic = useLocalLogic({ count, text });

  return <>
  // ...
}

API Reference

License

ISC