Skip to content

Repository files navigation

react-model · GitHub licensenpm versionminified sizeNode.js CIsizedownloadsCoverage StatusGreenkeeper badgePRs Welcome

The State management library for React

🎉 Support Both Class and Hooks Api

⚛️ Support preact, react-native and Next.js

⚔ Full TypeScript Support

📦 Built with microbundle

⚙️ Middleware Pipline ( redux-devtools support ... )

☂️ 100% test coverage, safe on production

🐛 Debug easily on test environment

import{useModel,createStore}from'react-model'// define modelconstuseTodo=()=>{const[items,setItems]=useModel(['Install react-model','Read github docs','Build App'])return{ items, setItems }}// Model Registerconst{ useStore }=createStore(useTodo)constApp=()=>{return<TodoList/>}constTodoList=()=>{const{ items, setItems }=useStore()return<div><Addonhandler={setItems}/>{state.items.map((item,index)=>(<Todokey={index}item={item}/>))}</div>}

Recently Updated

Quick Start

createStore + useModel

CodeSandbox: TodoMVC

Next.js + react-model work around

v2 docs

install package

npm install react-model

Table of Contents

Core Concept

createStore

You can create a shared / local store by createStore api.

Online Demo

model/counter.ts

import{useState}from'react'import{useModel}from'react-model'const{ useStore }=createStore(()=>{const[localCount,setLocalCount]=useState(1)// Local State, Independent in different componentsconst[count,setCount]=useModel(1)// Global State, the value is the same in different componentsconstincLocal=()=>{setLocalCount(localCount+1)}constinc=()=>{setCount(c=>c+1)}return{ count, localCount, incLocal, inc }})exportdefaultuseStore

page/counter-1.tsx

importuseSharedCounterfrom'models/global-counter'constPage=()=>{const{ count, localCount, inc, incLocal }=useStore()return<div><span>count: {count}</span><span>localCount: {localCount}</span><buttononClick={inc}>inc</button><buttononClick={incLocal}>incLocal</button></div>}

Model

Every model has its own state and actions.

constinitialState={counter: 0,light: false,response: {}}interfaceStateType{counter: numberlight: booleanresponse: {code?: numbermessage?: string}}interfaceActionsParamType{increment: numberopenLight: undefinedget: undefined}// You only need to tag the type of params here !constmodel: ModelType<StateType,ActionsParamType>={actions: {increment: async(payload,{ state })=>{return{counter: state.counter+(payload||1)}},openLight: async(_,{ state, actions })=>{awaitactions.increment(1)// You can use other actions within the modelawaitactions.get()// support async functions (block actions)actions.get()awaitactions.increment(1)// + 1awaitactions.increment(1)// + 2awaitactions.increment(1)// + 3 as expected !return{light: !state.light}},get: async()=>{awaitnewPromise((resolve,reject)=>setTimeout(()=>{resolve()},3000))return{response: {code: 200,message: `${newDate().toLocaleString()} open light success`}}}},state: initialState}exportdefaultmodel// You can use these types when use Class Components.// type ConsumerActionsType = getConsumerActionsType<typeof Model.actions>// type ConsumerType = { actions: ConsumerActionsType; state: StateType }// type ActionType = ConsumerActionsType// export { ConsumerType, StateType, ActionType }

⇧ back to top

Model Register

react-model keeps the application state and actions in separate private stores. So you need to register them if you want to use them as the public models.

model/index.ts

import{Model}from'react-model'importHomefrom'../model/home'importSharedfrom'../model/shared'constmodels={ Home, Shared }exportconst{ getInitialState, useStore, getState, actions, subscribe, unsubscribe }=Model(models)

⇧ back to top

useStore

The functional component in React ^16.8.0 can use Hooks to connect the global store. The actions returned from useStore can invoke dom changes.

The execution of actions returned by useStore will invoke the rerender of current component first.

It's the only difference between the actions returned by useStore and actions now.

importReactfrom'react'import{useStore}from'../index'// CSRexportdefault()=>{const[state,actions]=useStore('Home')const[sharedState,sharedActions]=useStore('Shared')return(<div>
Home model value: {JSON.stringify(state)}
Shared model value: {JSON.stringify(sharedState)}<buttononClick={e=>actions.increment(33)}>home increment</button><buttononClick={e=>sharedActions.increment(20)}>
shared increment
</button><buttononClick={e=>actions.get()}>fake request</button><buttononClick={e=>actions.openLight()}>fake nested call</button></div>)}

optional solution on huge dataset (example: TodoList(10000+ Todos)):

  1. use useStore on the subComponents which need it.
  2. use useStore selector. (version >= v4.0.0-rc.0)

advance example with 1000 todo items

⇧ back to top

getState

Key Point: State variable not updating in useEffect callback

To solve it, we provide a way to get the current state of model: getState

Note: the getState method cannot invoke the dom changes automatically by itself.

Hint: The state returned should only be used as readonly

import{useStore,getState}from'../model/index'constBasicHook=()=>{const[state,actions]=useStore('Counter')useEffect(()=>{console.log('some mounted actions from BasicHooks')return()=>console.log(`Basic Hooks unmounted, current Counter state: ${JSON.stringify(getState('Counter'))}`)},[])return(<><div>state: {JSON.stringify(state)}</div></>)}

⇧ back to top

actions

You can call other models' actions with actions api

actions can be used in both class components and functional components.

import{actions}from'./index'constmodel={state: {},actions: {crossModelCall: ()=>{actions.Shared.changeTheme('dark')actions.Counter.increment(9)}}}exportdefaultmodel

⇧ back to top

subscribe

subscribe(storeName, actions, callback) run the callback when the specific actions executed.

import{subscribe,unsubscribe}from'./index'constcallback=()=>{constuser=getState('User')localStorage.setItem('user_id',user.id)}// subscribe actionsubscribe('User','login',callback)// subscribe actionssubscribe('User',['login','logout'],callback)// unsubscribe the observer of some actionsunsubscribe('User','login')// only logout will run callback now

⇧ back to top

Advance Concept

immutable Actions

The actions use immer produce API to modify the Store. You can return a producer in action.

Using function as return value can make your code cleaner when you modify the deep nested value.

TypeScript Example

// StateType and ActionsParamType definition// ...constmodel: ModelType<StateType,ActionsParamType>={actions: {increment: async(params,{state: s})=>{// return (state: typeof s) => { // TypeScript < 3.9returnstate=>{state.counter+=params||1}},decrease: params=>s=>{s.counter+=params||1}}}exportdefaultmodel

JavaScript Example

constModel={actions: {increment: async(params)=>{returnstate=>{state.counter+=params||1}}}}

⇧ back to top

SSR with Next.js

Store: shared.ts

constinitialState={counter: 0}constmodel: ModelType<StateType,ActionsParamType>={actions: {increment: (params,{ state })=>{return{counter: state.counter+(params||1)}}},// Provide for SSRasyncState: asynccontext=>{awaitwaitFor(4000)return{counter: 500}},state: initialState}exportdefaultmodel

Global Config: _app.tsx

import{models,getInitialState,Models}from'../model/index'letpersistModel: anyinterfaceModelsProps{initialModels: ModelspersistModel: Models}constMyApp=(props: ModelsProps)=>{if((processasany).browser){// First come in: initialModels// After that: persistModelpersistModel=props.persistModel||Model(models,props.initialModels)}const{ Component, pageProps, router }=propsreturn(<Container><Component{...pageProps}/></Container>)}MyApp.getInitialProps=async(context: NextAppContext)=>{if(!(processasany).browser){constinitialModels=context.Component.getInitialProps
? awaitcontext.Component.getInitialProps(context.ctx)awaitgetInitialState(undefined,{isServer: true})// get all model initialState// : await getInitialState({ modelName: 'Home' }, { isServer: true }) // get Home initialState only// : await getInitialState({ modelName: ['Home', 'Todo'] }, { isServer: true }) // get multi initialState// : await getInitialState({ data }, { isServer: true }) // You can also pass some public data as asyncData params.return{initialModels}}else{return{persistModel}}}

Page: hooks/index.tsx

import{useStore,getState}from'../index'exportdefault()=>{const[state,actions]=useStore('Home')const[sharedState,sharedActions]=useStore('Shared')return(<div>
Home model value: {JSON.stringify(state)}
Shared model value: {JSON.stringify(sharedState)}<buttononClick={e=>{actions.increment(33)}}></div>
)
}

Single Page Config: benchmark.tsx

// ...Benchmark.getInitialProps=async()=>{returnawaitgetInitialState({modelName: 'Todo'},{isServer: true})}

⇧ back to top

Middleware

We always want to try catch all the actions, add common request params, connect Redux devtools and so on. We Provide the middleware pattern for developer to register their own Middleware to satisfy the specific requirement.

// Under the hoodconsttryCatch: Middleware<{}>=async(context,restMiddlewares)=>{const{ next }=contextawaitnext(restMiddlewares).catch((e: any)=>console.log(e))}// ...letactionMiddlewares=[tryCatch,getNewState,setNewState,stateUpdater,communicator,devToolsListener]// ...// How we execute an actionconstconsumerAction=(action: Action)=>async(params: any)=>{constcontext: Context={
modelName,
setState,actionName: action.name,next: ()=>{},newState: null,
params,
consumerActions,
action
}awaitapplyMiddlewares(actionMiddlewares,context)}// ...export{ ... ,actionMiddlewares}

⚙️ You can override the actionMiddlewares and insert your middleware to specific position

⇧ back to top

Expand Context

constExtCounter: ModelType<{name: string},// State Type{ext: undefined},// ActionParamsType{name: string}// ExtContextType>={actions: {// { state, action } => { state, action, [name] }ext: (_,{ name })=>{return{ name }}},state: {name: ''}}const{ useStore }=Model(ExtCounter,{name: 'test'})// state.name = ''const[state,actions]=useStore()// ...actions.ext()// state.name => 'test'

⇧ back to top

Other Concept required by Class Component

Provider

The global state standalone can not effect the react class components, we need to provide the state to react root component.

import{PureComponent}from'react'import{Provider}from'react-model'classAppextendsPureComponent{render(){return(<Provider><Counter/></Provider>)}}

⇧ back to top

connect

We can use the Provider state with connect.

Javascript decorator version

importReact,{PureComponent}from'react'import{Provider,connect}from'react-model'constmapProps=({ light, counter })=>({lightStatus: light ? 'open' : 'close',
counter
})// You can map the props in connect.
@connect('Home',mapProps)exportdefaultclassJSCounterextendsPureComponent{render(){const{ state, actions }=this.propsreturn(<><div>states - {JSON.stringify(state)}</div><buttononClick={e=>actions.increment(5)}>increment</button><buttononClick={e=>actions.openLight()}>Light Switch</button></>)}}

TypeScript Version

importReact,{PureComponent}from'react'import{Provider,connect}from'react-model'import{StateType,ActionType}from'../model/home'constmapProps=({ light, counter, response }: StateType)=>({lightStatus: light ? 'open' : 'close',
counter,
response
})typeRType=ReturnType<typeofmapProps>classTSCounterextendsPureComponent<{state: RType}&{actions: ActionType}>{render(){const{ state, actions }=this.propsreturn(<><div>TS Counter</div><div>states - {JSON.stringify(state)}</div><buttononClick={e=>actions.increment(3)}>increment</button><buttononClick={e=>actions.openLight()}>Light Switch</button><buttononClick={e=>actions.get()}>Get Response</button><div>message: {JSON.stringify(state.response)}</div></>)}}exportdefaultconnect('Home',mapProps)(TSCounter)

⇧ back to top

FAQ

Migrate from 4.0.x to 4.1.x

  1. replace Model with createStore

counter.ts

import{createStore}from'react-model'// Remove typedef below// type CounterState = {// count: number// }// type CounterActionParams = {// increment: number// }// v4.0.x modelconstCounter: ModelType<CounterState,CounterActionParams>={actions: {increment: (params)=>{return(state)=>{state.count+=params}}},state: {count: 0}}// v4.1.xconstCounter=createStore(()=>{const[state,setState]=useModel({count: 0})constactions={increment: (params)=>{setState((state)=>{state.count+=params})}}return[state,actions]asconst})exportdefaultCounter
  1. Remove Counter from model registry
constmodels={// Counter
Shared
}exportconst{ getInitialState, useStore, getState, actions, subscribe, unsubscribe }=Model(models)
  1. update useStore calls in components
// import { useStore } from 'models'importCounterfrom'models/counter'constComponent=()=>{// const [state, actions] = useStore('Counter')const[state,actions]=Counter.useStore()}

Migrate from 3.1.x to 4.x.x

  1. remove Model wrapper

sub-model.ts

// 3.1.xexportdefaultModel(model)// 4.x.xexportdefaultmodel

models.ts

importSubfrom'./sub-model'exportdefaultModel({ Sub })
  1. use selector to replace depActions

Shared.ts

interfaceState{counter: numberenable: boolean}interfaceActionParams{add: numberswitch: undefined}constmodel: ModelType<State,ActionParams>={state: {counter: 1enable: false},actions: {add: (payload)=>state=>{state.counter+=payload},switch: ()=>state=>{state.enable=!state.enable}}}
constComponent=()=>{// 3.1.x, Component rerender when add action is invokedconst[counter]=useStore('Shared',['add'])// 4.x.x, Component rerender when counter value diffconst[counter]=useStore('Shared',state=>state.counter)}

How can I disable the console debugger

import{middlewares}from'react-model'// Find the index of middleware// Disable all actions' logmiddlewares.config.logger.enable=false// Disable logs from specific type of actionsmiddlewares.config.logger.enable=({ actionName })=>['increment'].indexOf(actionName)!==-1

⇧ back to top

How can I add custom middleware

import{actionMiddlewares,middlewares,Model}from'react-model'import{sendLog}from'utils/log'importHomefrom'../model/home'importSharedfrom'../model/shared'// custom middlewareconstErrorHandler: Middleware=async(context,restMiddlewares)=>{const{ next }=contextawaitnext(restMiddlewares).catch((e: Error)=>sendLog(e))}// Find the index of middlewareconstgetNewStateMiddlewareIndex=actionMiddlewares.indexOf(middlewares.getNewState)// Replace itactionMiddlewares.splice(getNewStateMiddlewareIndex,0,ErrorHandler)conststores={ Home, Shared }exportdefaultModel(stores)

⇧ back to top

How can I make persist models

import{actionMiddlewares,Model}from'react-model'importExamplefrom'models/example'// Example, not recommend to use on production directly without consideration// Write current State to localStorage after action finishconstpersistMiddleware: Middleware=async(context,restMiddlewares)=>{localStorage.setItem('__REACT_MODEL__',JSON.stringify(context.Global.State))awaitcontext.next(restMiddlewares)}// Use on all modelsactionMiddlewares.push(persistMiddleware)Model({ Example },JSON.parse(localStorage.getItem('__REACT_MODEL__')))// Use on single modelconstmodel={state: JSON.parse(localStorage.getItem('__REACT_MODEL__'))['you model name']actions: { ... },middlewares: [...actionMiddlewares,persistMiddleware]}

⇧ back to top

How can I deal with local state

What should I do to make every Counter hold there own model? 🤔

classAppextendsComponent{render(){return(<divclassName="App"><Counter/><Counter/><Counter/></div>)}}
Counter model

interfaceState{count: number}interfaceActionParams{increment: number}constmodel: ModelType<State,ActionParams>={state: {count: 0},actions: {increment: payload=>{// immer.module.js:972 Uncaught (in promise) Error: An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft// Not allowed// return state => (state.count += payload)returnstate=>{state.count+=payload}}}}

Counter.tsx

constCounter=()=>{const[{ useStore }]=useState(()=>Model(model))const[state,actions]=useStore()return(<div><div>{state.count}</div><buttononClick={()=>actions.increment(3)}>Increment</button></div>)}exportdefaultCounter

⇧ back to top

How can I deal with huge dataset / circular dataset

Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, there should be no circular references.

Immer freezes everything recursively, for large data objects that won't be changed in the future this might be over-kill, in that case it can be more efficient to shallowly pre-freeze data using the freeze utility.

import{freeze}from'immer'exportconstExpensiveModel: ModelType<ExpensiveState,ExpensiveActionParams>={state: {moduleList: []},actions: {setPreFreezedDataset: ()=>{constoptimizedDataset=freeze(hugeDataset)return{moduleList: optimizedDataset}}}}

actions throw error from immer.module.js

immer.module.js:972 Uncaught (in promise) Error: An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft

How to fix:

actions: {increment: payload=>{// Not allowed// return state => (state.count += payload)returnstate=>{state.count+=payload}}}

⇧ back to top

How can I customize each model's middlewares?

You can customize each model's middlewares.

import{actionMiddlewares,Model}from'react-model'constdelayMiddleware: Middleware=async(context,restMiddlewares)=>{awaittimeout(1000,{})context.next(restMiddlewares)}constnextCounterModel: ModelType<CounterState,NextCounterActionParams>={actions: {add: num=>{returnstate=>{state.count+=num}},increment: async(num,{ actions })=>{actions.add(num)awaittimeout(300,{})}},// You can define the custom middlewares heremiddlewares: [delayMiddleware, ...actionMiddlewares],state: {count: 0}}exportdefaultModel(nextCounterModel)

⇧ back to top

About

The next generation state management library for React

Topics

Resources

Stars

235 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages