forgo-state
Easy Application State Management for Forgo Apps using JavaScript Proxies.
Installation
npm i forgo-state
Defining application state variables
First define one or more state variables using the defineState() API.
import { bindToStates, defineState } from "forgo-state";
const mailboxState = defineState({
messages: [],
drafts: [],
spam: [],
});
const signinState = defineState({
username: "",
lastActive: 0,
});
Binding components to your application state
Use bindToStates() while defining your Forgo components to bind one or more states to a specific component. In the following example, whenever mailboxState or signinState changes, the component is rerendered.
function MailboxView() {
return bindToStates([mailboxState, signinState], {
render(props: any, args: ForgoRenderArgs) {
return (
<div>
{state.messages.length ? (
state.messages.map((m) => <p>{m}</p>)
) : (
<p>There are no messages for {state.username}.</p>
)}
</div>
);
},
});
}
You could update the state properties any way you choose:
mailboxState.messages = data;
Binding components to specific properties of the state
Sometimes, you're interested in rerendering only when a specific property of the state changes. There's another api for this, bindToStateProps().
Usage is similar, but instead of an array of states you're interested in, you'll have to pass an array of [state, propertiesGetter] tuples.
Here's an example:
function MailboxView() {
return bindToStateProps(
[
[mailboxState, (state) => [state.messages, state.drafts]],
[signinState, (state) => [state.username]],
],
{
render(props: any, args: ForgoRenderArgs) {
return (
<div>
{state.messages.length ? (
state.messages.map((m) => <p>{m}</p>)
) : (
<p>There are no messages for {state.username}.</p>
)}
</div>
);
},
}
);
}