1.0.8 ā€¢ Published 2 years ago

@anissoft/state-react v1.0.8

Weekly downloads
6
License
MIT
Repository
github
Last release
2 years ago

Welcome to @anissoft/state-react šŸ‘‹

Installation

Just run npm install command:

$ npm install @anissoft/state-react --save

Usage

You can access state object in your React components via handy hook

import * as React from 'react';
import { useStateObject } from '@anissoft/state-react';

function Countdown(props: { start: number }) {
  const state = useStateObject({ timeLeft: start });

  React.useEffect(
    () => {
      const interval = setInterval(
        () => {
          if ( state.timeLeft === 0) {
            clearInterval(interval);
          } else {
           state.value.timeLeft = state.value.timeLeft - 1;
          }
        },
        1000,
      );

      return () => clearInterval(interval);
    [],
  );

  return (
    <div>
      <span>Seconds left {state.value.timeLeft}</span>
    </div>
  )
}

useStateObject can accept already created State object as agrument:

import * as React from "react";
import { useStateObject } from "@anissoft/state-react";

import myState from "Models/state";

function Component() {
  const state = useStateObject(myState);

  React.useEffect(() => {
    return myState.subscrube(() => {
      /* ... */
    });
  }, []);

  return <div>{/* ... */}</div>;
}

You can pass comparator as second argument, to specify condition when hook should initiate component rerender:

import * as React from "react";
import { useStateObject } from "@anissoft/state-react";

function Countdown({ timeout }: { timeout: number }) {
  const state = useuseStateObjectBox({ timeLeft: timeout }, (newValue) => newValue.timeLeft >= 0);

  React.useEffect(() => {
    const interval = setInterval(() => {
      state.value.timeLeft = state.value.timeLeft - 1;
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <span>{`Seconds left ${state.value.timeLeft}`}</span>
    </div>
  );
}

Author

šŸ‘¤ Alexey Anisimov

šŸ¤ Contributing

Contributions, issues and feature requests are welcome!

Feel free to check issues page.

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.4

2 years ago

1.0.3

3 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago

0.0.1

4 years ago