1.0.8 ā¢ Published 2 years ago
@anissoft/state-react v1.0.8
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
- Github: @Anissoft
š¤ Contributing
Contributions, issues and feature requests are welcome!
Feel free to check issues page.