Truth
A tiny state manager.
Setup
yarn add react-truth
Basic use
// state.jsimport ReactTruth from "react-truth"; public async { const res = await ; const data = await res; return ...thisstate data } // more actions ... ;
// Component.jsimport appState from "./state"; const state actions = appState; return <> <button =>Fetch Data</button> <div>Data: JSON</div> </> ;;
Advanced (Typescript)
// state.tsximport ReactTruth from "react-truth"; someValue: string = "initial from state class"; anotherValue?: string; <State> public async : Promise<State> return ...thisstate someValue: "mounted" public async : Promise<State> // you can set the state any time you need await this; // you can end this actions setting a state using // this.setState as usual or just return a value return ...thisstate someValue: newValue const initialState = ;const settings = persist: true actionsStatus: true; const myTruth = initialState settings; ;
// Component.tsximport appState from "./state"; const state actions = appState; const handleClick = actions; return <div> <button => Set a value statesomeValue </button> </div> ;;
Settings
persist:boolean = false
Persist the state in localStorage and recover it when the state starts.
persistanceKey:string = "persisted-state"
Used to name the localStorage item. default.
persistPick:string[] = null
Keys of persisted state members
actionsStatus:boolean = false
Generate automatic values in the state for actions status: state._status[actionName] A _status member need to be declared in the state.
// ... data: object; // add this member to your State _status: any; <State> public async : Promise<State> const res = await ; const data = await res; return ...thisstate data ; // ...
import state from "./state";import FIRED FAILED COMPLETED from "react-truth"; const state actions = state; const handleClick = actions; return <div> <button => state_statusapiCall == FIRED ? <span>The api call is happening</span> : state_statusapiCall == FAILED ? <span>Something went wrong</span> : state_statusapiCall == COMPLETED ? <span>Everything went ok!</span> : <span>nothing happens yet</span> </button> </div> ;;
debug:boolean = false
Log react-truth internals to the console
Truth Class
Any Truth instance has this methods to use or override
onLoad(): Promise
Is executed right when the Truth instance is created
setState(newState): Promise
Set the state with a new one. It´s async.
setStateRaw(newState): State
A sync state setter.
useState(pick:string[]): [State, actions]
React hook to plug a component to the state. A list of picked members of the state can be passed as unique param.
withState(Component: ReactComponent, stateResolver: (state)=> newState): ReactComponent
HOC to inject the state as props and the actions as action prop. A subset of the state can bi picked using a stateResolver
Redux devtools integration
Check what is happening in the state in the redux devtools.