1.0.8 ā€¢ Published 12 months ago

@anissoft/state-react v1.0.8

Weekly downloads
6
License
MIT
Repository
github
Last release
12 months 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

12 months ago

1.0.7

12 months ago

1.0.6

12 months ago

1.0.4

1 year ago

1.0.3

2 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago

0.0.1

3 years ago