All Projects → mjolnirjs → stated-bean

mjolnirjs / stated-bean

Licence: MIT License
A light but scalable view-model library with react hooks

Programming Languages

typescript
32286 projects
CSS
56736 projects

Projects that are alternatives of or similar to stated-bean

veact
Mutable state enhancer library for React based on @vuejs
Stars: ✭ 62 (+72.22%)
Mutual labels:  react-state-management, react-hooks
tacklebox
🎣React UX components for handling common interactions
Stars: ✭ 15 (-58.33%)
Mutual labels:  react-hooks
react-hook-geolocation
A React hook to access data from the Geolocation API
Stars: ✭ 31 (-13.89%)
Mutual labels:  react-hooks
hookstore
Hook based and lightweight centralized state management for React.
Stars: ✭ 28 (-22.22%)
Mutual labels:  react-hooks
7-react-admin-ts
用 ts + react-hooks 实现的管理后台
Stars: ✭ 23 (-36.11%)
Mutual labels:  react-hooks
react-hubspot
A collection of React hooks for interacting with Hubspot APIs
Stars: ✭ 20 (-44.44%)
Mutual labels:  react-hooks
book-fullstack-react
Fullstack React: The Complete Guide to ReactJS and Friends by Anthony Accomazzo
Stars: ✭ 100 (+177.78%)
Mutual labels:  react-hooks
foca
流畅的React状态管理库
Stars: ✭ 94 (+161.11%)
Mutual labels:  react-state-management
react-hooks-sse
Subscribe to an SSE endpoint with React Hooks
Stars: ✭ 60 (+66.67%)
Mutual labels:  react-hooks
pokehooks-labs
A laboratory to use pokemons and do some experiments with React Hooks API
Stars: ✭ 35 (-2.78%)
Mutual labels:  react-hooks
use-monaco
Use 🗒️ monaco-editor in any ⚛️ React app with simple hooks 🎣
Stars: ✭ 85 (+136.11%)
Mutual labels:  react-hooks
useReduction
useReducer without boilerplate
Stars: ✭ 36 (+0%)
Mutual labels:  react-hooks
use-breakpoint
React `useBreakpoint` hook to have different values for a variable based on a breakpoints.
Stars: ✭ 17 (-52.78%)
Mutual labels:  react-hooks
use-socket.io-client
https://www.npmjs.com/package/use-socket.io-client
Stars: ✭ 47 (+30.56%)
Mutual labels:  react-hooks
use-global-hook
Painless global state management for React using Hooks and Context API in 1KB!
Stars: ✭ 54 (+50%)
Mutual labels:  react-hooks
react-hooks-gatsby
Learn how to use React Hooks, and how they work with Gatsby. Watch the livestream:
Stars: ✭ 18 (-50%)
Mutual labels:  react-hooks
react-click-away-listener
🐾 Tiny React Click Away Listener built with React Hooks
Stars: ✭ 131 (+263.89%)
Mutual labels:  react-hooks
react-native-react-bridge
An easy way to integrate your React (or Preact) app into React Native app with WebView.
Stars: ✭ 84 (+133.33%)
Mutual labels:  react-hooks
useAudioPlayer
Custom React hook & context for controlling browser audio
Stars: ✭ 176 (+388.89%)
Mutual labels:  react-hooks
react-hook-layout
Layouts in React.
Stars: ✭ 16 (-55.56%)
Mutual labels:  react-hooks

stated-bean

Travis Codecov type-coverage npm GitHub release

David Peer David David Dev

Conventional Commits code style: prettier codechecks.io

A light but scalable view-model library with react hooks.

TOC

# yarn
yarn add stated-bean

# npm
npm i stated-bean

Features

  • OOP: easy to integrate with DI(dependency inject) framework together
  • Familiar API: just provider and hooks
  • Small size: npm bundle size npm bundle size
  • Written in TypeScript

Online Demo

GitHub Pages: Integration with injection-js

Usage

Define a StatedBean

Plain object StatedBean

import { useBean } from 'stated-bean';

const CounterModel = {
  count: 0,
  decrement() {
    this.count--;
  },
  increment() {
    this.count++;
  },
};

function CounterDisplay() {
  const counter = useBean(() => CounterModel);

  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <span>{counter.count}</span>
      <button onClick={counter.increment}>+</button>
    </div>
  );
}

function App() {
  return (
    <StatedBeanProvider>
      <CounterDisplay />
    </StatedBeanProvider>
  );
}

Class StatedBean

import { StatedBean, Stated useBean } from 'stated-bean';

@StatedBean()
class CounterModel {
  @Stated()
  count = 0;

  increment() {
    this.count++;
  }

  decrement() {
    this.count--;
  }
}

function CounterDisplay() {
  const counter = useBean(CounterModel);

  return (
    // ...
  );
}

Singleton and Named StatedBean

The named bean singleton bean can be resolved via useInject with the special name.

Define a named bean

@StatedBean('SpecialName')
class NamedBean {}

@StatedBean({ singleton: true })
class SingletonBean {}

Declare as a named bean by useBean

const model = useBean(CounterModel, { name: 'SpecialName' });

Provider container and inject the singleton bean

The beans was stored in the StatedBeanContainer witch be created by the StatedBeanProvider and bind to the React context. useInject will find the named bean from the container or it's parent container.

@StatedBean({ singleton: true })
class UserModel {
  @Stated()
  user = { name: 'jack' };
}

function App() {
  return (
    <StatedBeanProvider providers={[UserModel]}>
      <UserDisplay />
    </StatedBeanProvider>
  );
}

function UserDisplay() {
  const model = useInject(UserModel);

  return model.user.name;
}

Auto inject and watch the props

@StatedBean()
class InputModel implements InitializingBean {
  @Props('initialValue')
  @Stated()
  value: number;

  @ObservableProps()
  value$: BehaviorSubject<number>;

  afterProvided() {
    this.value$.subscribe(v => {
      this.value = v;
    });
  }
}

function Input(props: InputProps) {
  const model = useBean(InputModel, { props });

  return (
    // input component
  );
}

Effect action state and observer

@StatedBean()
class SearchModel {

  @Effect()
  search() {
    return fetchUsers();
  }
}

const UserTable() {
  const model = useBean(SearchModel);
  const { loading, error } = useObserveEffect(model, "search");

  if (loading) {
    return <Loading />;
  }
  return (
    // ...user table
  );
}

API

Decorators

StatedBean

Signature: @StatedBean(name?: string | symbol): ClassDecorator

Indicates that an annotated class is a StatedBean. The name may indicate a suggestion for the bean name. Its default value is Class.name.

Stated

Signature: @Stated(): PropertyDecorator

Indicates that an annotated property is Stated. Its reassignment will be observed and notified to the container.

AfterProvided

Signature: @AfterProvided(): MethodDecorator

The AfterProvided decorator is used on a method that needs to be executed after the StatedBean be instanced to perform any initialization.

Effect

Signature: @Effect(name?: string | symbol): MethodDecorator

The Effect decorator is used on a method that can get the execution state by useObserveEffect.

Props and ObservableProps

Signature: @Props(name?: string): PropertyDecorator @ObservableProps(name?: string): PropertyDecorator

The Props decorator is used on a property that can sync the value from props. The ObservableProps decorator is used on a BehaviorSubject property. You can subscribe the next new props value.

use Hooks

useBean

Signature: useBean<T>(typeOrSupplier: ClassType<T> | () => T, name?: string | symbol): T

The useBean will create an instance of the stated bean with a new StatedBeanContainer and listen for its data changes to trigger the re-rendering of the current component.

useInject

Signature: useInject<T>(type: ClassType<T>, option: UseStatedBeanOption<T> = {}): T

The useInject will get the instance of the stated bean from the StatedBeanContainer in the context and listen for its data changes to trigger the re-rendering of the current component.

UseStatedBeanOption
option = {
  name: string | symbol;   // get/create the instance with special name
  dependentFields: Array<string | symbol>;   // do re-render when the special property changed
};

useObserveEffect

Signature: useObserveEffect(bean: StatedBeanType, name: string | symbol): EffectAction

observe the execution state of the method which with @Effect.

Provider

<StatedBeanProvider {...props: StatedBeanProviderProps} />

The StatedBeanProvider is responsible for creating an instance of the stated bean and dispatching an event after data changes.

StatedBeanProviderProps

interface StatedBeanProviderProps {
  types?: ClassType[];
  beans?: Array<StatedBeanType<unknown>>;
  beanProvider?: BeanProvider;
  application?: StatedBeanApplication;
}

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].