State
Params:
initValue
, getInitValue
, next
Next value:
An object with attributes:
value
, change
, onChange
Sample:
import * as React from "react";
import {cs, State} from "cs-react";
const Example = () => cs(
["count", ({}, next) => State({initValue: 0, next})],
({count})=>(
<div>
Count: {count.value}
<button
onClick={()=>count.change((v)=>v+1)}
>+</button>
<button
onClick={()=>count.change((v)=>v-1)}
>-</button>
</div>
),
);
Here is the CodePen demo
Both "change" and "onChange" functions are asynchronous, which means right after you change the state, the state.value won't be changed immediately, instead, the change is scheduled and will be applied in future. For example:
import * as React from "react";
import {cs, State} from "cs-react";
const Example = () => cs(
["state", ({}, next) => State({initValue: "old value", next})],
({state})=>(
<div>
<div>
Current: {state.value}
</div>
<button
onClick={()=> {
state.onChange("new value");
console.log(state.value);
// This console.log code above will print "old value" (first time only)
}}
>Change to "new value"</button>
</div>
),
);
Here is the CodePen demo