├── .codecov.yml ├── .github ├── ISSUE_TEMPLATE │ ├── custom.md │ └── issue-template.md └── workflows │ └── node.js.yml ├── .gitignore ├── .npmignore ├── .prettierrc ├── .remarkrc ├── .travis.yml ├── README.md ├── __test__ ├── Model │ ├── error.multi.spec.ts │ ├── error.spec.ts │ ├── errorModel.ts │ ├── extContext.multi.spec.ts │ ├── extContext.spec.single.ts │ ├── mixed.spec.ts │ ├── return.spec.ts │ ├── same-name.spec.ts │ ├── share-setState.spec.ts │ └── single.spec.ts ├── SSR │ └── index.spec.ts ├── actions │ ├── actions.spec.ts │ ├── getActions.spec.ts │ ├── unmount.spec.ts │ └── useStore.spec.ts ├── asyncState.spec.ts ├── class │ ├── class.spec.tsx │ ├── communicator.spec.tsx │ ├── mapActions.spec.tsx │ └── renderProps.spec.tsx ├── connect.spec.tsx ├── disable-dubugger.spec.ts ├── dubugger.spec.ts ├── getActions.spec.ts ├── getState.spec.ts ├── index.d.ts ├── index.ts ├── lane │ ├── lane.spec.ts │ ├── migrate.spec.ts │ └── react.spec.ts ├── middlewares │ ├── commuicator.spec.ts │ ├── devToolsListener.spec.ts │ ├── getNewStateWithCache.spec.ts │ ├── middlewareConfig.spec.ts │ ├── model.spec.ts │ ├── subscribe.spec.ts │ ├── tryCatch.spec.ts │ └── unsubscribe.spec.ts ├── performance │ └── deep-expensive-mutation.spec.tsx ├── selector │ ├── model.spec.ts │ ├── models.spec.ts │ └── shallowEqual.spec.ts └── useStore │ ├── actions.spec.ts │ ├── initial.spec.ts │ └── initialModels.spec.ts ├── commitlint.config.js ├── jest.config.js ├── package.json ├── src ├── global.ts ├── helper.ts ├── index.d.ts ├── index.tsx └── middlewares.ts ├── tsconfig.json ├── tslint.json └── yarn.lock /.codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | branch: master 3 | 4 | coverage: 5 | status: 6 | project: 7 | default: 8 | # Fail the status if coverage drops by >= 0.1% 9 | threshold: 0.1 -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 'Issue Template (Chinese)' 3 | about: '规范的issue可以帮助我们更好地定位问题' 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 我有一个: 11 | 12 | 1. [ ] 问题: 我们很乐意解决你遇到的问题.😄 13 | 14 | 2. [ ] 文档补充/修正. 欢迎提PR修正👏. 15 | 16 | 2. [ ] Issue: 17 | 18 | * [ ] **请提供完整的报错信息** ❌ 19 | 20 | * [ ] 请提供issue的**最小**复现单元. **你可以在这个[sandbox](https://codesandbox.io/s/moyxon99jx)基础上补充复现问题的代码** 🚀 21 | 22 | * [ ] 你是否确定这个问题没有在issue区被提过? 🤔 23 | 24 | * [ ] 请详细描述你的issue. 你期望的行为是什么 ❓ 25 | 26 | * [ ] 请提供你使用的react-model版本和issue复现所需的环境. (浏览器 / node / 操作系统 / react 版本? 🚧 27 | 28 | | 依赖环境 | 版本(s) | 29 | | ---------------- | ---------- | 30 | | react-model | | 31 | | Node | | 32 | | react | | 33 | | Operating System | | 34 | 35 | 3. [ ] 好主意、想加入的新feature: 36 | * [ ] 它可以解决什么问题? 🐛 37 | * [ ] 你认为它应该被集成在这个库中,还是以文档的方式说明,还是其他方式体现? 💡 38 | * [ ] 你是否乐意自己提PR来完成这个feature呢? ⚔ 39 | 40 | 勾选你的问题所属的类型,issue模板中其他无关的部分记得删除哦 41 | 42 | **issue被解决后,希望你可以及时关闭issue :)** 43 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/issue-template.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Issue Template 3 | about: Good issue can help others to position problem easily. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | I have a: 11 | 12 | 1. [ ] Question: Feel free to just state your question.😄 13 | 14 | 2. [ ] Documentation improvement. Creating a PR if you can👏. 15 | 16 | 2. [ ] Issue: 17 | 18 | * [ ] **Provide error messages including stacktrace** ❌ 19 | 20 | * [ ] Provide a **minimal** sample reproduction. **Create a reproduction based on this [sandbox](https://codesandbox.io/s/moyxon99jx)** 🚀 21 | * [ ] Did you check this issue wasn't filed before? 🤔 22 | 23 | * [ ] Elaborate on your issue. What behavior did you expect? ❓ 24 | 25 | * [ ] State the versions of react-model and relevant libraries. Which browser / node / ... version? 🚧 26 | 27 | | Software | Version(s) | 28 | | ---------------- | ---------- | 29 | | react-model | | 30 | | Node | | 31 | | react | | 32 | | Operating System | | 33 | 34 | 3. [ ] Idea: 35 | 36 | * [ ] What problem would it solve for you? 🐛 37 | * [ ] Do you think others will benefit from this change as well and it should in core package? 💡 38 | * [ ] Are you willing to (attempt) a PR yourself? ⚔ 39 | 40 | Please tick the appropriate boxes. Feel free to remove the _other_ sections. 41 | 42 | **Please be sure to close your issues promptly.** 43 | -------------------------------------------------------------------------------- /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [ main, dev ] 9 | pull_request: 10 | branches: [ main, dev ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: self-hosted 16 | 17 | strategy: 18 | matrix: 19 | node-version: [12.x, 14.x, 16.x] 20 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v2 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | cache: 'yarn' 29 | - run: yarn 30 | - run: yarn global add codecov 31 | - run: yarn test:coverage 32 | - run: codecov -f coverage/*.json 33 | - run: bash <(curl -s https://codecov.io/bash) 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Next.js 2 | .next/ 3 | node_modules/ 4 | 5 | # Parcel 6 | .cache/ 7 | 8 | # package 9 | *.tgz 10 | 11 | # VSCode 12 | .vscode/ 13 | 14 | # Compile 15 | dist/ 16 | 17 | # microbundle 18 | .rts2_cache_cjs/ 19 | .rts2_cache_es/ 20 | .rts2_cache_umd/ 21 | 22 | # yarn 23 | package-lock.json 24 | 25 | # Jest 26 | coverage/ 27 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Next.js 2 | .next/ 3 | node_modules/ 4 | 5 | # Parcel 6 | .cache/ 7 | 8 | # Example 9 | example/ 10 | 11 | # package 12 | *.tgz 13 | 14 | # yarn 15 | yarn.lock 16 | package-lock.json 17 | 18 | # VSCode 19 | .vscode/ 20 | 21 | # Test 22 | __test__/ 23 | jest.config.js 24 | coverage/ 25 | 26 | # microbundle 27 | .rts2_cache_cjs/ 28 | .rts2_cache_es/ 29 | .rts2_cache_umd/ 30 | 31 | # Github 32 | .github/ 33 | .git/ -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "tabWidth": 2, 4 | "useTabs": false, 5 | "semi": false, 6 | "parser": "babylon", 7 | "singleQuote": true, 8 | "trailingComma": "none", 9 | "bracketSpacing": true, 10 | "jsxBracketSameLine": false, 11 | "overrides": [ 12 | { 13 | "files": ".prettierrc", 14 | "options": { "parser": "json", "trailingComma": "none" } 15 | }, 16 | { 17 | "files": ".babelrc", 18 | "options": { "parser": "json", "trailingComma": "none" } 19 | }, 20 | { 21 | "files": "*.ts", 22 | "options": { "parser": "typescript", "trailingComma": "none" } 23 | }, 24 | { 25 | "files": "*.tsx", 26 | "options": { "parser": "typescript", "trailingComma": "none" } 27 | }, 28 | { 29 | "files": "*.json", 30 | "options": { "parser": "json", "trailingComma": "none" } 31 | } 32 | ] 33 | } -------------------------------------------------------------------------------- /.remarkrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "remark-preset-lint-recommended", 4 | ["remark-lint-list-item-indent", "space"] 5 | ] 6 | } -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '10' 4 | - '11' 5 | - '12' 6 | - '13' 7 | - '14' 8 | 9 | before_script: 10 | - npm install react@latest react-dom@latest 11 | - npm install codecov -g 12 | 13 | after_success: 14 | - npm run test:coverage 15 | - codecov -f coverage/*.json 16 | - bash <(curl -s https://codecov.io/bash) 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-model · ![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg) [![npm version](https://img.shields.io/npm/v/react-model.svg?style=flat)](https://www.npmjs.com/package/react-model) [![minified size](https://badgen.net/bundlephobia/min/react)](https://bundlephobia.com/result?p=react-model) [![Node.js CI](https://github.com/byte-fe/react-model/actions/workflows/node.js.yml/badge.svg?branch=main)](https://github.com/byte-fe/react-model/actions/workflows/node.js.yml) [![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/react-model/dist/react-model.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/react-model/dist/react-model.js) [![downloads](https://img.shields.io/npm/dt/react-model.svg)](https://www.npmjs.com/package/react-model) [![Coverage Status](https://codecov.io/gh/byte-fe/react-model/branch/master/graph/badge.svg)](https://codecov.io/gh/byte-fe/react-model) [![Greenkeeper badge](https://badges.greenkeeper.io/byte-fe/react-model.svg)](https://greenkeeper.io/) ![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg) 2 | 3 | The State management library for React 4 | 5 | 🎉 Support Both Class and Hooks Api 6 | 7 | ⚛️ Support [preact](https://github.com/byte-fe/react-model-experiment/tree/preact), react-native and Next.js 8 | 9 | ⚔ Full TypeScript Support 10 | 11 | 📦 Built with microbundle 12 | 13 | ⚙️ Middleware Pipline ( redux-devtools support ... ) 14 | 15 | ☂️ 100% test coverage, safe on production 16 | 17 | 🐛 Debug easily on test environment 18 | 19 | ```tsx 20 | import { useModel, createStore } from 'react-model' 21 | 22 | // define model 23 | const useTodo = () => { 24 | const [items, setItems] = useModel(['Install react-model', 'Read github docs', 'Build App']) 25 | return { items, setItems } 26 | } 27 | 28 | // Model Register 29 | const { useStore } = createStore(useTodo) 30 | 31 | const App = () => { 32 | return 33 | } 34 | 35 | const TodoList = () => { 36 | const { items, setItems } = useStore() 37 | return
38 | 39 | {state.items.map((item, index) => ())} 40 |
41 | } 42 | ``` 43 | 44 | --- 45 | 46 | ## Recently Updated 47 | 48 | * [feat(middleware): support enable/disable sepecific middleware](#how-can-i-disable-the-console-debugger) 49 | * fix(stateupdater): fix the issue that setState on unmounted component 50 | 51 | ## Quick Start 52 | 53 | [createStore + useModel](https://codesandbox.io/s/createstore-usemodal-all-of-your-state-4u8s6) 54 | 55 | [CodeSandbox: TodoMVC](https://codesandbox.io/s/moyxon99jx) 56 | 57 | [Next.js + react-model work around](https://github.com/byte-fe/react-model-experiment) 58 | 59 | [v2 docs](https://github.com/byte-fe/react-model/blob/v2/README.md) 60 | 61 | install package 62 | 63 | ```shell 64 | npm install react-model 65 | ``` 66 | 67 | ## Table of Contents 68 | 69 | - [Core Concept](#core-concept) 70 | - [createStore](#createstore) 71 | - [Model](#model) 72 | - [Model Register](#model-register) 73 | - [useStore](#usestore) 74 | - [getState](#getstate) 75 | - [actions](#actions) 76 | - [subscribe](#subscribe) 77 | - [Advance Concept](#advance-concept) 78 | - [immutable Actions](#immutable-actions) 79 | - [SSR with Next.js](#ssr-with-nextjs) 80 | - [Middleware](#middleware) 81 | - [Expand Context](#expand-context) 82 | - [Other Concept required by Class Component](#other-concept-required-by-class-component) 83 | - [Provider](#provider) 84 | - [connect](#connect) 85 | - [FAQ](#faq) 86 | - [Migrate from 4.0.x to 4.1.x](#migrate-from-40x-to-41x) 87 | - [Migrate from 3.1.x to 4.x.x](#migrate-from-31x-to-4xx) 88 | - [How can I disable the console debugger?](#how-can-i-disable-the-console-debugger) 89 | - [How can I add custom middleware](#how-can-i-add-custom-middleware) 90 | - [How can I make persist models](#how-can-i-make-persist-models) 91 | - [How can I deal with local state](#how-can-i-deal-with-local-state) 92 | - [How can I deal with huge dataset / circular dataset](#how-can-i-deal-with-huge-dataset--circular-dataset) 93 | - [actions throw error from immer.module.js](#actions-throw-error-from-immermodulejs) 94 | - [How can I customize each model's middlewares?](#how-can-i-customize-each-models-middlewares) 95 | 96 | ## Core Concept 97 | 98 | ### createStore 99 | 100 | You can create a shared / local store by createStore api. 101 | 102 | [Online Demo](https://codesandbox.io/s/createstore-usemodal-all-of-your-state-4u8s6) 103 | 104 | `model/counter.ts` 105 | 106 | ```typescript 107 | import { useState } from 'react' 108 | import { useModel } from 'react-model' 109 | const { useStore } = createStore(() => { 110 | const [localCount, setLocalCount] = useState(1) // Local State, Independent in different components 111 | const [count, setCount] = useModel(1) // Global State, the value is the same in different components 112 | const incLocal = () => { 113 | setLocalCount(localCount + 1) 114 | } 115 | const inc = () => { 116 | setCount(c => c + 1) 117 | } 118 | return { count, localCount, incLocal, inc } 119 | }) 120 | 121 | export default useStore 122 | ``` 123 | 124 | `page/counter-1.tsx` 125 | 126 | ```tsx 127 | import useSharedCounter from 'models/global-counter' 128 | const Page = () => { 129 | const { count, localCount, inc, incLocal } = useStore() 130 | return
131 | count: { count } 132 | localCount: { localCount } 133 | 134 | 135 |
136 | } 137 | ``` 138 | 139 | ### Model 140 | 141 | Every model has its own state and actions. 142 | 143 | ```typescript 144 | const initialState = { 145 | counter: 0, 146 | light: false, 147 | response: {} 148 | } 149 | 150 | interface StateType { 151 | counter: number 152 | light: boolean 153 | response: { 154 | code?: number 155 | message?: string 156 | } 157 | } 158 | 159 | interface ActionsParamType { 160 | increment: number 161 | openLight: undefined 162 | get: undefined 163 | } // You only need to tag the type of params here ! 164 | 165 | const model: ModelType = { 166 | actions: { 167 | increment: async (payload, { state }) => { 168 | return { 169 | counter: state.counter + (payload || 1) 170 | } 171 | }, 172 | openLight: async (_, { state, actions }) => { 173 | await actions.increment(1) // You can use other actions within the model 174 | await actions.get() // support async functions (block actions) 175 | actions.get() 176 | await actions.increment(1) // + 1 177 | await actions.increment(1) // + 2 178 | await actions.increment(1) // + 3 as expected ! 179 | return { light: !state.light } 180 | }, 181 | get: async () => { 182 | await new Promise((resolve, reject) => 183 | setTimeout(() => { 184 | resolve() 185 | }, 3000) 186 | ) 187 | return { 188 | response: { 189 | code: 200, 190 | message: `${new Date().toLocaleString()} open light success` 191 | } 192 | } 193 | } 194 | }, 195 | state: initialState 196 | } 197 | 198 | export default model 199 | 200 | // You can use these types when use Class Components. 201 | // type ConsumerActionsType = getConsumerActionsType 202 | // type ConsumerType = { actions: ConsumerActionsType; state: StateType } 203 | // type ActionType = ConsumerActionsType 204 | // export { ConsumerType, StateType, ActionType } 205 | ``` 206 | 207 | [⇧ back to top](#table-of-contents) 208 | 209 | ### Model Register 210 | 211 | 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. 212 | 213 | `model/index.ts` 214 | 215 | ```typescript 216 | import { Model } from 'react-model' 217 | import Home from '../model/home' 218 | import Shared from '../model/shared' 219 | 220 | const models = { Home, Shared } 221 | 222 | export const { getInitialState, useStore, getState, actions, subscribe, unsubscribe } = Model(models) 223 | ``` 224 | 225 | [⇧ back to top](#table-of-contents) 226 | 227 | ### useStore 228 | 229 | The functional component in React ^16.8.0 can use Hooks to connect the global store. 230 | The actions returned from useStore can invoke dom changes. 231 | 232 | The execution of actions returned by useStore will invoke the rerender of current component first. 233 | 234 | It's the only difference between the actions returned by useStore and actions now. 235 | 236 | ```tsx 237 | import React from 'react' 238 | import { useStore } from '../index' 239 | 240 | // CSR 241 | export default () => { 242 | const [state, actions] = useStore('Home') 243 | const [sharedState, sharedActions] = useStore('Shared') 244 | 245 | return ( 246 |
247 | Home model value: {JSON.stringify(state)} 248 | Shared model value: {JSON.stringify(sharedState)} 249 | 250 | 253 | 254 | 255 |
256 | ) 257 | } 258 | ``` 259 | 260 | optional solution on huge dataset (example: TodoList(10000+ Todos)): 261 | 262 | 1. use useStore on the subComponents which need it. 263 | 2. use useStore selector. (version >= v4.0.0-rc.0) 264 | 265 | [advance example with 1000 todo items](https://codesandbox.io/s/react-model-v4-todomvc-oxyij) 266 | 267 | [⇧ back to top](#table-of-contents) 268 | 269 | ### getState 270 | 271 | Key Point: [State variable not updating in useEffect callback](https://github.com/facebook/react/issues/14066) 272 | 273 | To solve it, we provide a way to get the current state of model: getState 274 | 275 | Note: the getState method cannot invoke the dom changes automatically by itself. 276 | 277 | > Hint: The state returned should only be used as readonly 278 | 279 | ```jsx 280 | import { useStore, getState } from '../model/index' 281 | 282 | const BasicHook = () => { 283 | const [state, actions] = useStore('Counter') 284 | useEffect(() => { 285 | console.log('some mounted actions from BasicHooks') 286 | return () => 287 | console.log( 288 | `Basic Hooks unmounted, current Counter state: ${JSON.stringify( 289 | getState('Counter') 290 | )}` 291 | ) 292 | }, []) 293 | return ( 294 | <> 295 |
state: {JSON.stringify(state)}
296 | 297 | ) 298 | } 299 | ``` 300 | 301 | [⇧ back to top](#table-of-contents) 302 | 303 | ### actions 304 | 305 | You can call other models' actions with actions api 306 | 307 | actions can be used in both class components and functional components. 308 | 309 | ```js 310 | import { actions } from './index' 311 | 312 | const model = { 313 | state: {}, 314 | actions: { 315 | crossModelCall: () => { 316 | actions.Shared.changeTheme('dark') 317 | actions.Counter.increment(9) 318 | } 319 | } 320 | } 321 | 322 | export default model 323 | ``` 324 | 325 | [⇧ back to top](#table-of-contents) 326 | 327 | ### subscribe 328 | 329 | subscribe(storeName, actions, callback) run the callback when the specific actions executed. 330 | 331 | ```typescript 332 | import { subscribe, unsubscribe } from './index' 333 | 334 | const callback = () => { 335 | const user = getState('User') 336 | localStorage.setItem('user_id', user.id) 337 | } 338 | 339 | // subscribe action 340 | subscribe('User', 'login', callback) 341 | // subscribe actions 342 | subscribe('User', ['login', 'logout'], callback) 343 | // unsubscribe the observer of some actions 344 | unsubscribe('User', 'login') // only logout will run callback now 345 | ``` 346 | 347 | [⇧ back to top](#table-of-contents) 348 | 349 | ## Advance Concept 350 | 351 | ### immutable Actions 352 | 353 | The actions use [immer](https://github.com/mweststrate/immer) produce API to modify the Store. You can return a producer in action. 354 | 355 | Using function as return value can make your code cleaner when you modify the deep nested value. 356 | 357 | TypeScript Example 358 | 359 | ```ts 360 | // StateType and ActionsParamType definition 361 | // ... 362 | 363 | const model: ModelType = { 364 | actions: { 365 | increment: async (params, { state: s }) => { 366 | // return (state: typeof s) => { // TypeScript < 3.9 367 | return state => { 368 | state.counter += params || 1 369 | } 370 | }, 371 | decrease: params => s => { 372 | s.counter += params || 1 373 | } 374 | } 375 | } 376 | 377 | export default model 378 | ``` 379 | 380 | JavaScript Example 381 | 382 | ```js 383 | const Model = { 384 | actions: { 385 | increment: async (params) => { 386 | return state => { 387 | state.counter += params || 1 388 | } 389 | } 390 | } 391 | } 392 | ``` 393 | 394 | [⇧ back to top](#table-of-contents) 395 | 396 | ### SSR with Next.js 397 | 398 |
399 | Store: shared.ts 400 |

401 | 402 | ```ts 403 | const initialState = { 404 | counter: 0 405 | } 406 | 407 | const model: ModelType = { 408 | actions: { 409 | increment: (params, { state }) => { 410 | return { 411 | counter: state.counter + (params || 1) 412 | } 413 | } 414 | }, 415 | // Provide for SSR 416 | asyncState: async context => { 417 | await waitFor(4000) 418 | return { counter: 500 } 419 | }, 420 | state: initialState 421 | } 422 | 423 | export default model 424 | ``` 425 | 426 |

427 |
428 | 429 |
430 | Global Config: _app.tsx 431 |

432 | 433 | 434 | ```tsx 435 | import { models, getInitialState, Models } from '../model/index' 436 | 437 | let persistModel: any 438 | 439 | interface ModelsProps { 440 | initialModels: Models 441 | persistModel: Models 442 | } 443 | 444 | const MyApp = (props: ModelsProps) => { 445 | if ((process as any).browser) { 446 | // First come in: initialModels 447 | // After that: persistModel 448 | persistModel = props.persistModel || Model(models, props.initialModels) 449 | } 450 | const { Component, pageProps, router } = props 451 | return ( 452 | 453 | 454 | 455 | ) 456 | } 457 | 458 | MyApp.getInitialProps = async (context: NextAppContext) => { 459 | if (!(process as any).browser) { 460 | const initialModels = context.Component.getInitialProps 461 | ? await context.Component.getInitialProps(context.ctx) 462 | await getInitialState(undefined, { isServer: true }) // get all model initialState 463 | // : await getInitialState({ modelName: 'Home' }, { isServer: true }) // get Home initialState only 464 | // : await getInitialState({ modelName: ['Home', 'Todo'] }, { isServer: true }) // get multi initialState 465 | // : await getInitialState({ data }, { isServer: true }) // You can also pass some public data as asyncData params. 466 | return { initialModels } 467 | } else { 468 | return { persistModel } 469 | } 470 | } 471 | ``` 472 |

473 |
474 | 475 |
476 | Page: hooks/index.tsx 477 |

478 | 479 | ```tsx 480 | import { useStore, getState } from '../index' 481 | export default () => { 482 | const [state, actions] = useStore('Home') 483 | const [sharedState, sharedActions] = useStore('Shared') 484 | 485 | return ( 486 |

487 | Home model value: {JSON.stringify(state)} 488 | Shared model value: {JSON.stringify(sharedState)} 489 |
495 | ) 496 | } 497 | ``` 498 |

499 |
500 | 501 |
502 | Single Page Config: benchmark.tsx 503 |

504 | 505 | ```tsx 506 | // ... 507 | Benchmark.getInitialProps = async () => { 508 | return await getInitialState({ modelName: 'Todo' }, { isServer: true }) 509 | } 510 | ``` 511 |

512 |
513 | 514 | [⇧ back to top](#table-of-contents) 515 | 516 | ### Middleware 517 | 518 | 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. 519 | 520 | ```tsx 521 | // Under the hood 522 | const tryCatch: Middleware<{}> = async (context, restMiddlewares) => { 523 | const { next } = context 524 | await next(restMiddlewares).catch((e: any) => console.log(e)) 525 | } 526 | 527 | // ... 528 | 529 | let actionMiddlewares = [ 530 | tryCatch, 531 | getNewState, 532 | setNewState, 533 | stateUpdater, 534 | communicator, 535 | devToolsListener 536 | ] 537 | 538 | // ... 539 | // How we execute an action 540 | const consumerAction = (action: Action) => async (params: any) => { 541 | const context: Context = { 542 | modelName, 543 | setState, 544 | actionName: action.name, 545 | next: () => {}, 546 | newState: null, 547 | params, 548 | consumerActions, 549 | action 550 | } 551 | await applyMiddlewares(actionMiddlewares, context) 552 | } 553 | 554 | // ... 555 | 556 | export { ... , actionMiddlewares} 557 | ``` 558 | 559 | ⚙️ You can override the actionMiddlewares and insert your middleware to specific position 560 | 561 | [⇧ back to top](#table-of-contents) 562 | 563 | ### Expand Context 564 | 565 | ```typescript 566 | const ExtCounter: ModelType< 567 | { name: string }, // State Type 568 | { ext: undefined }, // ActionParamsType 569 | { name: string } // ExtContextType 570 | > = { 571 | actions: { 572 | // { state, action } => { state, action, [name] } 573 | ext: (_, { name }) => { 574 | return { name } 575 | } 576 | }, 577 | state: { name: '' } 578 | } 579 | 580 | const { useStore } = Model(ExtCounter, { name: 'test' }) 581 | // state.name = '' 582 | const [state, actions] = useStore() 583 | // ... 584 | actions.ext() 585 | // state.name => 'test' 586 | ``` 587 | 588 | [⇧ back to top](#table-of-contents) 589 | 590 | ## Other Concept required by Class Component 591 | 592 | ### Provider 593 | 594 | The global state standalone can not effect the react class components, we need to provide the state to react root component. 595 | 596 | ```jsx 597 | import { PureComponent } from 'react' 598 | import { Provider } from 'react-model' 599 | 600 | class App extends PureComponent { 601 | render() { 602 | return ( 603 | 604 | 605 | 606 | ) 607 | } 608 | } 609 | ``` 610 | 611 | [⇧ back to top](#table-of-contents) 612 | 613 | ### connect 614 | 615 | We can use the Provider state with connect. 616 | 617 |
618 | Javascript decorator version 619 |

620 | 621 | ```jsx 622 | import React, { PureComponent } from 'react' 623 | import { Provider, connect } from 'react-model' 624 | 625 | const mapProps = ({ light, counter }) => ({ 626 | lightStatus: light ? 'open' : 'close', 627 | counter 628 | }) // You can map the props in connect. 629 | 630 | @connect( 631 | 'Home', 632 | mapProps 633 | ) 634 | export default class JSCounter extends PureComponent { 635 | render() { 636 | const { state, actions } = this.props 637 | return ( 638 | <> 639 |

states - {JSON.stringify(state)}
640 | 641 | 642 | 643 | ) 644 | } 645 | } 646 | ``` 647 | 648 |

649 |
650 | 651 |
652 | TypeScript Version 653 |

654 | 655 | ```tsx 656 | import React, { PureComponent } from 'react' 657 | import { Provider, connect } from 'react-model' 658 | import { StateType, ActionType } from '../model/home' 659 | 660 | const mapProps = ({ light, counter, response }: StateType) => ({ 661 | lightStatus: light ? 'open' : 'close', 662 | counter, 663 | response 664 | }) 665 | 666 | type RType = ReturnType 667 | 668 | class TSCounter extends PureComponent< 669 | { state: RType } & { actions: ActionType } 670 | > { 671 | render() { 672 | const { state, actions } = this.props 673 | return ( 674 | <> 675 |

TS Counter
676 |
states - {JSON.stringify(state)}
677 | 678 | 679 | 680 |
message: {JSON.stringify(state.response)}
681 | 682 | ) 683 | } 684 | } 685 | 686 | export default connect( 687 | 'Home', 688 | mapProps 689 | )(TSCounter) 690 | ``` 691 |

692 |
693 | 694 | [⇧ back to top](#table-of-contents) 695 | 696 | ## FAQ 697 | 698 | ### Migrate from 4.0.x to 4.1.x 699 | 700 | 1. replace Model with createStore 701 | 702 | `counter.ts` 703 | 704 | ```ts 705 | import { createStore } from 'react-model' 706 | // Remove typedef below 707 | // type CounterState = { 708 | // count: number 709 | // } 710 | 711 | // type CounterActionParams = { 712 | // increment: number 713 | // } 714 | 715 | // v4.0.x model 716 | const Counter: ModelType< 717 | CounterState, 718 | CounterActionParams 719 | > = { 720 | actions: { 721 | increment: (params) => { 722 | return (state) => { 723 | state.count += params 724 | } 725 | } 726 | }, 727 | state: { count: 0 } 728 | } 729 | 730 | // v4.1.x 731 | const Counter = createStore(() => { 732 | const [state, setState] = useModel({ count: 0 }) 733 | const actions = { 734 | increment: (params) => { 735 | setState((state) => { 736 | state.count += params 737 | }) 738 | } 739 | } 740 | return [state, actions] as const 741 | }) 742 | 743 | export default Counter 744 | ``` 745 | 746 | 2. Remove Counter from model registry 747 | 748 | ```ts 749 | const models = { 750 | // Counter 751 | Shared 752 | } 753 | 754 | export const { getInitialState, useStore, getState, actions, subscribe, unsubscribe } = Model(models) 755 | ``` 756 | 757 | 3. update useStore calls in components 758 | 759 | ```tsx 760 | // import { useStore } from 'models' 761 | import Counter from 'models/counter' 762 | 763 | const Component = () => { 764 | // const [state, actions] = useStore('Counter') 765 | const [state, actions] = Counter.useStore() 766 | } 767 | ``` 768 | 769 | ### Migrate from 3.1.x to 4.x.x 770 | 771 | 1. remove Model wrapper 772 | 773 | `sub-model.ts` 774 | ```ts 775 | // 3.1.x 776 | export default Model(model) 777 | // 4.x.x 778 | export default model 779 | ``` 780 | 781 | `models.ts` 782 | ```ts 783 | import Sub from './sub-model' 784 | export default Model({ Sub }) 785 | ``` 786 | 787 | 2. use selector to replace depActions 788 | 789 | `Shared.ts` 790 | ```ts 791 | interface State { 792 | counter: number 793 | enable: boolean 794 | } 795 | 796 | interface ActionParams { 797 | add: number 798 | switch: undefined 799 | } 800 | 801 | const model: ModelType = { 802 | state: { 803 | counter: 1 804 | enable: false 805 | }, 806 | actions: { 807 | add: (payload) => state => { 808 | state.counter += payload 809 | }, 810 | switch: () => state => { 811 | state.enable = !state.enable 812 | } 813 | } 814 | } 815 | ``` 816 | 817 | ```ts 818 | const Component = () => { 819 | // 3.1.x, Component rerender when add action is invoked 820 | const [counter] = useStore('Shared', ['add']) 821 | // 4.x.x, Component rerender when counter value diff 822 | const [counter] = useStore('Shared', state => state.counter) 823 | } 824 | ``` 825 | 826 | ### How can I disable the console debugger 827 | 828 | 829 | ```typescript 830 | import { middlewares } from 'react-model' 831 | // Find the index of middleware 832 | 833 | // Disable all actions' log 834 | middlewares.config.logger.enable = false 835 | // Disable logs from specific type of actions 836 | middlewares.config.logger.enable = ({ actionName }) => ['increment'].indexOf(actionName) !== -1 837 | ``` 838 | 839 | [⇧ back to top](#table-of-contents) 840 | 841 | ### How can I add custom middleware 842 | 843 | ```typescript 844 | import { actionMiddlewares, middlewares, Model } from 'react-model' 845 | import { sendLog } from 'utils/log' 846 | import Home from '../model/home' 847 | import Shared from '../model/shared' 848 | 849 | // custom middleware 850 | const ErrorHandler: Middleware = async (context, restMiddlewares) => { 851 | const { next } = context 852 | await next(restMiddlewares).catch((e: Error) => sendLog(e)) 853 | } 854 | 855 | // Find the index of middleware 856 | const getNewStateMiddlewareIndex = actionMiddlewares.indexOf( 857 | middlewares.getNewState 858 | ) 859 | 860 | // Replace it 861 | actionMiddlewares.splice(getNewStateMiddlewareIndex, 0, ErrorHandler) 862 | 863 | const stores = { Home, Shared } 864 | 865 | export default Model(stores) 866 | ``` 867 | 868 | [⇧ back to top](#table-of-contents) 869 | 870 | #### How can I make persist models 871 | 872 | ```typescript 873 | import { actionMiddlewares, Model } from 'react-model' 874 | import Example from 'models/example' 875 | 876 | // Example, not recommend to use on production directly without consideration 877 | // Write current State to localStorage after action finish 878 | const persistMiddleware: Middleware = async (context, restMiddlewares) => { 879 | localStorage.setItem('__REACT_MODEL__', JSON.stringify(context.Global.State)) 880 | await context.next(restMiddlewares) 881 | } 882 | 883 | // Use on all models 884 | actionMiddlewares.push(persistMiddleware) 885 | Model({ Example }, JSON.parse(localStorage.getItem('__REACT_MODEL__'))) 886 | 887 | // Use on single model 888 | const model = { 889 | state: JSON.parse(localStorage.getItem('__REACT_MODEL__'))['you model name'] 890 | actions: { ... }, 891 | middlewares: [...actionMiddlewares, persistMiddleware] 892 | } 893 | 894 | 895 | ``` 896 | 897 | [⇧ back to top](#table-of-contents) 898 | 899 | ### How can I deal with local state 900 | 901 | What should I do to make every Counter hold there own model? 🤔 902 | 903 | ```tsx 904 | class App extends Component { 905 | render() { 906 | return ( 907 |
908 | 909 | 910 | 911 |
912 | ) 913 | } 914 | } 915 | ``` 916 | 917 |
918 | Counter model 919 |

920 | 921 | ```ts 922 | interface State { 923 | count: number 924 | } 925 | 926 | interface ActionParams { 927 | increment: number 928 | } 929 | 930 | const model: ModelType = { 931 | state: { 932 | count: 0 933 | }, 934 | actions: { 935 | increment: payload => { 936 | // 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 937 | // Not allowed 938 | // return state => (state.count += payload) 939 | return state => { 940 | state.count += payload 941 | } 942 | } 943 | } 944 | } 945 | 946 | ``` 947 | 948 |

949 |
950 | 951 |
952 | Counter.tsx 953 |

954 | 955 | ```tsx 956 | 957 | const Counter = () => { 958 | const [{ useStore }] = useState(() => Model(model)) 959 | const [state, actions] = useStore() 960 | return ( 961 |

962 |
{state.count}
963 | 964 |
965 | ) 966 | } 967 | 968 | export default Counter 969 | ``` 970 | 971 |

972 |
973 | 974 | [⇧ back to top](#table-of-contents) 975 | 976 | ### How can I deal with huge dataset / circular dataset 977 | 978 | [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.](https://immerjs.github.io/immer/pitfalls#immer-only-supports-unidirectional-trees) 979 | 980 | 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. 981 | 982 | ```ts 983 | import { freeze } from 'immer' 984 | 985 | export const ExpensiveModel: ModelType = { 986 | state: { 987 | moduleList: [] 988 | }, 989 | actions: { 990 | setPreFreezedDataset: () => { 991 | const optimizedDataset = freeze(hugeDataset) 992 | return { moduleList: optimizedDataset } 993 | } 994 | } 995 | } 996 | ``` 997 | 998 | ### actions throw error from immer.module.js 999 | 1000 | ``` 1001 | 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 1002 | ``` 1003 | 1004 | How to fix: 1005 | 1006 | ```tsx 1007 | actions: { 1008 | increment: payload => { 1009 | // Not allowed 1010 | // return state => (state.count += payload) 1011 | return state => { 1012 | state.count += payload 1013 | } 1014 | } 1015 | } 1016 | ``` 1017 | 1018 | [⇧ back to top](#table-of-contents) 1019 | 1020 | ### How can I customize each model's middlewares? 1021 | 1022 | You can customize each model's middlewares. 1023 | 1024 | ```typescript 1025 | import { actionMiddlewares, Model } from 'react-model' 1026 | const delayMiddleware: Middleware = async (context, restMiddlewares) => { 1027 | await timeout(1000, {}) 1028 | context.next(restMiddlewares) 1029 | } 1030 | 1031 | const nextCounterModel: ModelType = { 1032 | actions: { 1033 | add: num => { 1034 | return state => { 1035 | state.count += num 1036 | } 1037 | }, 1038 | increment: async (num, { actions }) => { 1039 | actions.add(num) 1040 | await timeout(300, {}) 1041 | } 1042 | }, 1043 | // You can define the custom middlewares here 1044 | middlewares: [delayMiddleware, ...actionMiddlewares], 1045 | state: { 1046 | count: 0 1047 | } 1048 | } 1049 | 1050 | export default Model(nextCounterModel) 1051 | ``` 1052 | 1053 | [⇧ back to top](#table-of-contents) 1054 | -------------------------------------------------------------------------------- /__test__/Model/error.multi.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | // @ts-ignore 4 | import { ErrorModel as EM } from './errorModel' 5 | import { Model } from '../../src' 6 | 7 | describe('useStore', () => { 8 | test('create by single model error definition', async () => { 9 | let state: any 10 | let actions: any 11 | let count = 0 12 | const ErrorModel = Model(EM) 13 | // @ts-ignore 14 | const { useStore, subscribe, unsubscribe } = Model({ ErrorModel }) 15 | renderHook(() => { 16 | ;[state, actions] = useStore('ErrorModel') 17 | }) 18 | expect(actions).toEqual({}) 19 | expect(actions.increment).toBe(undefined) 20 | // await actions.increment(3) 21 | expect(state).toEqual({}) 22 | // test subscribe 23 | // @ts-ignore 24 | subscribe('increment', () => (count += 1)) 25 | expect(count).toBe(0) 26 | expect(state.count).toBe(undefined) 27 | // test unsubscribe 28 | // @ts-ignore 29 | unsubscribe('increment') 30 | expect(actions).toEqual({}) 31 | expect(state.count).toBe(undefined) 32 | expect(count).toBe(0) 33 | }) 34 | }) 35 | -------------------------------------------------------------------------------- /__test__/Model/error.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | // @ts-ignore 4 | import { ErrorModel } from './errorModel' 5 | import { Model } from '../../src' 6 | 7 | describe('useStore', () => { 8 | test('create by single model definition', async () => { 9 | let state: any 10 | let actions: any 11 | let count = 0 12 | // @ts-ignore 13 | const { useStore, subscribe, unsubscribe } = Model(ErrorModel) 14 | renderHook(() => { 15 | ;[state, actions] = useStore() 16 | }) 17 | expect(state).toEqual({}) 18 | expect(actions.increment).toBe(undefined) 19 | // await actions.increment(3) 20 | expect(state).toEqual({}) 21 | // test subscribe 22 | subscribe('increment', () => (count += 1)) 23 | expect(actions).toEqual({}) 24 | expect(count).toBe(0) 25 | expect(state.count).toBe(undefined) 26 | // test unsubscribe 27 | unsubscribe('increment') 28 | expect(actions).toEqual({}) 29 | expect(state.count).toBe(undefined) 30 | expect(count).toBe(0) 31 | }) 32 | }) 33 | -------------------------------------------------------------------------------- /__test__/Model/errorModel.ts: -------------------------------------------------------------------------------- 1 | // Use to simulate a error model.js file 2 | export const ErrorModel: any = { 3 | actions: { 4 | // @ts-ignore 5 | add: (params, { state }) => { 6 | return { 7 | count: state.count + params 8 | } 9 | }, 10 | // @ts-ignore 11 | addCaller: (_, { actions }) => { 12 | actions.add(5) 13 | }, 14 | // @ts-ignore 15 | increment: params => { 16 | // @ts-ignore 17 | return state => { 18 | state.count += params 19 | } 20 | }, 21 | state: { count: 0 } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /__test__/Model/extContext.multi.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | import { ExtCounter } from '..' 4 | import { Model } from '../../src' 5 | 6 | describe('useStore', () => { 7 | test('models with extContext', async () => { 8 | // Multiple Model with Context 9 | let testState: any 10 | let testActions: any 11 | let extState: any 12 | let extActions: any 13 | // @ts-ignore 14 | const Test = Model(ExtCounter, { name: 'test' }) 15 | // @ts-ignore 16 | const Ext = Model(ExtCounter, { name: 'ext' }) 17 | const { useStore } = Model({ Test, Ext }) 18 | renderHook(() => { 19 | ;[testState, testActions] = useStore('Test') 20 | ;[extState, extActions] = useStore('Ext') 21 | }) 22 | expect(testState).toEqual({ name: '' }) 23 | await testActions.ext() 24 | expect(testState).toEqual({ name: 'test' }) 25 | expect(extState).toEqual({ name: '' }) 26 | await extActions.ext() 27 | expect(extState).toEqual({ name: 'ext' }) 28 | }) 29 | }) 30 | -------------------------------------------------------------------------------- /__test__/Model/extContext.spec.single.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | import { ExtCounter } from '..' 4 | import { Model } from '../../src' 5 | 6 | describe('useStore', () => { 7 | test('models with extContext', async () => { 8 | // Single Model extContext 9 | let state: any 10 | let actions: any 11 | const { useStore: u } = Model(ExtCounter, { name: 'test' }) 12 | renderHook(() => { 13 | ;[state, actions] = u() 14 | }) 15 | expect(state).toEqual({ name: '' }) 16 | await actions.ext() 17 | expect(state).toEqual({ name: 'test' }) 18 | }) 19 | }) 20 | -------------------------------------------------------------------------------- /__test__/Model/mixed.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | import { NextCounter } from '..' 4 | import { Model } from '../../src' 5 | 6 | describe('useStore', () => { 7 | test('create by single model definition', async () => { 8 | let state: any, nextState: any 9 | let actions: any, nextActions: any 10 | let count = 0 11 | let nextCount = 0 12 | const Home = Model(NextCounter) 13 | const { useStore, subscribe, unsubscribe } = Model({ Home, NextCounter }) 14 | renderHook(() => { 15 | ;[state, actions] = useStore('Home') 16 | ;[nextState, nextActions] = useStore('NextCounter') 17 | }) 18 | 19 | // Home 20 | expect(state).toEqual({ count: 0 }) 21 | await actions.increment(3) 22 | expect(state).toEqual({ count: 3 }) 23 | // test subscribe 24 | subscribe('Home', 'increment', () => (count += 1)) 25 | await actions.increment(4) 26 | expect(count).toBe(1) 27 | expect(state.count).toBe(7) 28 | // test unsubscribe 29 | unsubscribe('Home', 'increment') 30 | await actions.increment(3) 31 | expect(state.count).toBe(10) 32 | expect(count).toBe(1) 33 | 34 | // NextCounter 35 | expect(nextState).toEqual({ count: 0 }) 36 | await nextActions.increment(3) 37 | expect(nextState).toEqual({ count: 3 }) 38 | // test subscribe 39 | subscribe('NextCounter', 'increment', () => (nextCount += 1)) 40 | await nextActions.increment(4) 41 | expect(nextCount).toBe(1) 42 | expect(nextState.count).toBe(7) 43 | // test unsubscribe 44 | unsubscribe('NextCounter', 'increment') 45 | await nextActions.increment(3) 46 | expect(nextState.count).toBe(10) 47 | expect(nextCount).toBe(1) 48 | }) 49 | }) 50 | -------------------------------------------------------------------------------- /__test__/Model/return.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook, act } from '@testing-library/react-hooks' 3 | import { RetTester } from '..' 4 | import { Model } from '../../src' 5 | 6 | describe('action return value', () => { 7 | test('return object value', async () => { 8 | let actions: any 9 | const { useStore } = Model(RetTester) 10 | renderHook(() => { 11 | ;[, actions] = useStore() 12 | }) 13 | await act(async () => { 14 | const retVal = await actions.add(5) 15 | expect(retVal).toEqual({ count: 5 }) 16 | const retVal_2 = await actions.add(5) 17 | expect(retVal).toEqual({ count: 5 }) 18 | expect(retVal_2).toEqual({ count: 10 }) 19 | }) 20 | }) 21 | 22 | test('return promise value', async () => { 23 | let actions: any 24 | const { useStore } = Model(RetTester) 25 | renderHook(() => { 26 | ;[, actions] = useStore() 27 | }) 28 | await act(async () => { 29 | const retVal = await actions.asyncAdd(5) 30 | expect(retVal).toEqual({ count: 5 }) 31 | const retVal_2 = await actions.asyncAdd(5) 32 | expect(retVal).toEqual({ count: 5 }) 33 | expect(retVal_2).toEqual({ count: 10 }) 34 | }) 35 | }) 36 | 37 | test('return produce function', async () => { 38 | const asyncPrototype = Object.getPrototypeOf(async () => {}) 39 | const isAsync = (input: unknown) => { 40 | return Object.getPrototypeOf(input) === asyncPrototype 41 | } 42 | let actions: any 43 | const { useStore } = Model(RetTester) 44 | renderHook(() => { 45 | ;[, actions] = useStore() 46 | }) 47 | await act(async () => { 48 | const retVal = await actions.produceAdd(5) 49 | expect(isAsync(retVal)).toBe(true) 50 | const retVal_2 = await actions.produceAdd(5) 51 | expect(isAsync(retVal)).toBe(true) 52 | expect(isAsync(retVal_2)).toBe(true) 53 | }) 54 | }) 55 | 56 | test('return async produce function', async () => { 57 | const asyncPrototype = Object.getPrototypeOf(async () => {}) 58 | const isAsync = (input: unknown) => { 59 | return Object.getPrototypeOf(input) === asyncPrototype 60 | } 61 | let actions: any 62 | const { useStore } = Model(RetTester) 63 | renderHook(() => { 64 | ;[, actions] = useStore() 65 | }) 66 | await act(async () => { 67 | const retVal = await actions.asyncProduceAdd(5) 68 | expect(isAsync(retVal)).toBe(true) 69 | const retVal_2 = await actions.asyncProduceAdd(5) 70 | expect(isAsync(retVal)).toBe(true) 71 | expect(isAsync(retVal_2)).toBe(true) 72 | }) 73 | }) 74 | 75 | test('return action', async () => { 76 | let actions: any 77 | const { useStore } = Model(RetTester) 78 | renderHook(() => { 79 | ;[, actions] = useStore() 80 | }) 81 | await act(async () => { 82 | const retVal = await actions.hocAdd(5) 83 | expect(retVal).toEqual({ count: 5 }) 84 | const retVal_2 = await actions.hocAdd(5) 85 | expect(retVal).toEqual({ count: 5 }) 86 | expect(retVal_2).toEqual({ count: 10 }) 87 | }) 88 | }) 89 | 90 | test('return async action', async () => { 91 | let actions: any 92 | const { useStore } = Model(RetTester) 93 | renderHook(() => { 94 | ;[, actions] = useStore() 95 | }) 96 | await act(async () => { 97 | const retVal = await actions.asyncHocAdd(5) 98 | expect(retVal).toEqual({ count: 5 }) 99 | const retVal_2 = await actions.asyncHocAdd(5) 100 | expect(retVal).toEqual({ count: 5 }) 101 | expect(retVal_2).toEqual({ count: 10 }) 102 | }) 103 | }) 104 | }) 105 | -------------------------------------------------------------------------------- /__test__/Model/same-name.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | import { NextCounter } from '..' 4 | import { Model } from '../../src' 5 | 6 | describe('useStore', () => { 7 | test('create by single model definition', async () => { 8 | let state: any 9 | let actions: any 10 | let mirrorState: any 11 | let mirrorActions: any 12 | let count = 0 13 | const { useStore, subscribe, unsubscribe, getState } = Model({ 14 | NextCounter 15 | }) 16 | const { 17 | useStore: useMirrorStore, 18 | subscribe: mirrorSubscribe, 19 | unsubscribe: mirrorUnSubscribe, 20 | getState: getMirrorState 21 | } = Model({ NextCounter }) 22 | renderHook(() => { 23 | ;[state, actions] = useStore('NextCounter') 24 | ;[mirrorState, mirrorActions] = useMirrorStore('NextCounter') 25 | }) 26 | expect(state).toEqual({ count: 0 }) 27 | expect(mirrorState).toEqual({ count: 0 }) 28 | 29 | mirrorSubscribe('NextCounter', 'increment', () => (count += 1)) 30 | 31 | await actions.increment(3) 32 | expect(state).toEqual({ count: 3 }) 33 | expect(mirrorState).toEqual({ count: 0 }) 34 | expect(count).toBe(0) 35 | 36 | await mirrorActions.increment(3) 37 | expect(state).toEqual({ count: 3 }) 38 | expect(mirrorState).toEqual({ count: 3 }) 39 | expect(count).toBe(1) 40 | 41 | // test subscribe 42 | subscribe('NextCounter', 'increment', () => (count += 1)) 43 | await actions.increment(4) 44 | expect(count).toBe(2) 45 | expect(state.count).toBe(7) 46 | expect(mirrorState.count).toBe(3) 47 | expect(getState('NextCounter').count).toBe(7) 48 | expect(getMirrorState('NextCounter').count).toBe(3) 49 | 50 | // test unsubscribe 51 | unsubscribe('NextCounter', 'increment') 52 | mirrorUnSubscribe('NextCounter', 'increment') 53 | await actions.increment(3) 54 | expect(state.count).toBe(10) 55 | expect(mirrorState.count).toBe(3) 56 | expect(getState('NextCounter').count).toBe(10) 57 | expect(getMirrorState('NextCounter').count).toBe(3) 58 | expect(count).toBe(2) 59 | }) 60 | }) 61 | -------------------------------------------------------------------------------- /__test__/Model/share-setState.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | import { State } from '..' 4 | import { Model } from '../../src' 5 | 6 | describe('common used case', () => { 7 | test('create by single model with common setState', async () => { 8 | let state: any 9 | let actions: any 10 | let failed = false 11 | const { useStore, getState } = Model(State) 12 | renderHook(() => { 13 | ;[state, actions] = useStore() 14 | }) 15 | expect(state).toEqual({ xxx: '', yyy: -1 }) 16 | await actions.setState({ yyy: 3 }) 17 | expect(state).toEqual({ xxx: '', yyy: 3 }) 18 | // @ts-ignore 19 | await actions.setState(state => { 20 | state.yyy = 1 21 | }) 22 | expect(state.yyy).toBe(1) 23 | expect(getState().xxx).toBe("") 24 | expect(getState().yyy).toBe(1) 25 | 26 | expect(failed).toBe(false) 27 | 28 | try { 29 | // BAD USE CASE 30 | // 1. use both return value and produce modifier 31 | // @ts-ignore 32 | await actions.setState((state) => { 33 | state.xxx = "xxx" 34 | return { yyy: 10 } 35 | }) 36 | // nothing changed 37 | expect(state.yyy).toBe(1) 38 | expect(getState().xxx).toBe("") 39 | } catch { 40 | failed = true 41 | } 42 | 43 | expect(failed).toBe(true) 44 | 45 | // 2. return partial value in produce func 46 | // @ts-ignore 47 | await actions.setState(() => { 48 | return { yyy: 10 } 49 | }) 50 | // key xxx will be dropped 51 | expect(state.yyy).toBe(10) 52 | expect(getState().xxx).toBe(undefined) 53 | 54 | }) 55 | }) 56 | -------------------------------------------------------------------------------- /__test__/Model/single.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | import { NextCounter } from '..' 4 | import { Model } from '../../src' 5 | 6 | describe('useStore', () => { 7 | test('create by single model definition', async () => { 8 | let state: any 9 | let actions: any 10 | let count = 0 11 | const { useStore, subscribe, unsubscribe, getState } = Model(NextCounter) 12 | renderHook(() => { 13 | ;[state, actions] = useStore() 14 | }) 15 | expect(state).toEqual({ count: 0 }) 16 | await actions.increment(3) 17 | expect(state).toEqual({ count: 3 }) 18 | // test subscribe 19 | subscribe('increment', () => (count += 1)) 20 | await actions.increment(4) 21 | expect(count).toBe(1) 22 | expect(state.count).toBe(7) 23 | expect(getState().count).toBe(7) 24 | // test unsubscribe 25 | unsubscribe('increment') 26 | await actions.increment(3) 27 | expect(state.count).toBe(10) 28 | expect(getState().count).toBe(10) 29 | expect(count).toBe(1) 30 | }) 31 | }) 32 | -------------------------------------------------------------------------------- /__test__/SSR/index.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { Model } from '../../src' 3 | import { SSRCounter } from '..' 4 | 5 | describe('asyncState', () => { 6 | test('return default initial state from asyncState', async () => { 7 | const { getInitialState } = Model({ 8 | WrappedSSRCounter: Model(SSRCounter), 9 | SSRCounter 10 | }) 11 | const initialModels = await getInitialState(undefined, { isServer: true }) 12 | // const state = getState('AsyncCounter') 13 | expect(initialModels['SSRCounter'].count).toBe(1) 14 | expect(initialModels['SSRCounter'].clientKey).toBe(undefined) 15 | expect(initialModels['WrappedSSRCounter'].count).toBe(1) 16 | expect(initialModels['WrappedSSRCounter'].clientKey).toBe(undefined) 17 | 18 | // Simulate Client Side 19 | const { getState } = Model( 20 | { WrappedSSRCounter: Model(SSRCounter), SSRCounter }, 21 | initialModels 22 | ) 23 | expect(initialModels['SSRCounter'].count).toBe(1) 24 | expect(initialModels['WrappedSSRCounter'].count).toBe(1) 25 | expect(getState('SSRCounter').clientKey).toBe('unused') 26 | expect(getState('WrappedSSRCounter').clientKey).toBe('unused') 27 | }) 28 | }) 29 | -------------------------------------------------------------------------------- /__test__/actions/actions.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | import { Model } from '../../src' 4 | import { ActionsTester } from '../index' 5 | 6 | describe('actions', () => { 7 | test('get actions from Model', async () => { 8 | const { actions, useStore } = Model({ ActionsTester }) 9 | let state: any 10 | renderHook(() => { 11 | ;[state] = useStore('ActionsTester') 12 | }) 13 | await actions.ActionsTester.getData() 14 | expect(state.data).toEqual({ counter: 1000 }) 15 | }) 16 | }) 17 | -------------------------------------------------------------------------------- /__test__/actions/getActions.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | import { ActionsTester } from '../index' 4 | import { Model } from '../../src' 5 | 6 | describe('actions', () => { 7 | test('call actions in action', async () => { 8 | const { getActions, getState } = Model({ ActionsTester }) 9 | let state: any 10 | let actions: any 11 | renderHook(() => { 12 | actions = getActions('ActionsTester') 13 | }) 14 | await actions.getData() 15 | state = getState('ActionsTester') 16 | expect(state.data).toEqual({ counter: 1000 }) 17 | }) 18 | }) 19 | -------------------------------------------------------------------------------- /__test__/actions/unmount.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | import { ActionsTester } from '../index' 4 | import { Model } from '../../src' 5 | 6 | describe('actions', () => { 7 | test('call actions in action', async () => { 8 | const { useStore } = Model({ ActionsTester }) 9 | let state: any 10 | let actions: any 11 | const { unmount } = renderHook(() => { 12 | ;[state, actions] = useStore('ActionsTester') 13 | }) 14 | await actions.getData() 15 | unmount() 16 | expect(state.data).toEqual({ counter: 1000 }) 17 | }) 18 | }) 19 | -------------------------------------------------------------------------------- /__test__/actions/useStore.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { renderHook } from '@testing-library/react-hooks' 3 | import { ActionsTester } from '../index' 4 | import { Model } from '../../src' 5 | 6 | describe('actions', () => { 7 | test('call actions in action', async () => { 8 | const { useStore } = Model({ ActionsTester }) 9 | let state: any 10 | let actions: any 11 | renderHook(() => { 12 | ;[state, actions] = useStore('ActionsTester') 13 | }) 14 | await actions.getData() 15 | expect(state.data).toEqual({ counter: 1000 }) 16 | }) 17 | }) 18 | -------------------------------------------------------------------------------- /__test__/asyncState.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { Model } from '../src' 3 | import { AsyncCounter, AsyncNull } from '.' 4 | 5 | describe('asyncState', () => { 6 | test('asyncState accept context params with error modelName', async () => { 7 | const { getInitialState, getState } = Model({ AsyncCounter }) 8 | await getInitialState({ count: 2, modelName: 'Async' }) 9 | const state = getState('AsyncCounter') 10 | expect(state.count).toBe(0) 11 | }) 12 | test('return default initial state from asyncState', async () => { 13 | const { getState, getInitialState } = Model({ AsyncCounter }) 14 | await getInitialState() 15 | const state = getState('AsyncCounter') 16 | expect(state.count).toBe(1) 17 | }) 18 | test('asyncState accept context params', async () => { 19 | const { getInitialState, getState } = Model({ AsyncCounter }) 20 | await getInitialState({ count: 2 }) 21 | const state = getState('AsyncCounter') 22 | expect(state.count).toBe(2) 23 | }) 24 | test('asyncState accept context params with modelName', async () => { 25 | const { getInitialState, getState } = Model({ AsyncCounter }) 26 | await getInitialState({ count: 3, modelName: 'AsyncCounter' }) 27 | const state = getState('AsyncCounter') 28 | expect(state.count).toBe(3) 29 | }) 30 | test('asyncState work without asyncState', async () => { 31 | const { getInitialState, getState } = Model({ AsyncNull }) 32 | await getInitialState() 33 | const state = getState('AsyncNull') 34 | expect(state.count).toBe(0) 35 | }) 36 | }) 37 | -------------------------------------------------------------------------------- /__test__/class/class.spec.tsx: -------------------------------------------------------------------------------- 1 | /// 2 | import * as React from 'react' 3 | import { Model, Provider, connect } from '../../src' 4 | import { Counter } from '../index' 5 | import { render, fireEvent } from '@testing-library/react' 6 | import { timeout } from '../../src/helper' 7 | 8 | const Button = connect( 9 | 'Counter', 10 | (props: any) => props 11 | )( 12 | class extends React.PureComponent { 13 | render() { 14 | const { state, actions } = this.props 15 | return ( 16 | 23 | ) 24 | } 25 | } 26 | ) 27 | 28 | describe('class component', () => { 29 | test('Provider', () => { 30 | Model({ Counter }) 31 | const { container } = render( 32 | 33 | 24 | ) 25 | } 26 | } 27 | ) 28 | 29 | describe('class component', () => { 30 | test('communicator', async () => { 31 | let state: any 32 | const { useStore } = Model({ Counter }) 33 | renderHook(() => { 34 | ;[state] = useStore('Counter') 35 | }) 36 | const { container } = render( 37 | 38 | 26 | ) 27 | } 28 | } 29 | ) 30 | 31 | describe('class component', () => { 32 | test('render props', () => { 33 | Model({ Counter }) 34 | const { container } = render( 35 | 36 | 23 | ) 24 | } 25 | } 26 | ) 27 | 28 | describe('class component', () => { 29 | test('render props', () => { 30 | Model({ Counter }) 31 | const { container } = render( 32 | 33 | 23 | ) 24 | } 25 | } 26 | ) 27 | ) 28 | 29 | describe('class component', () => { 30 | test('multi connect', async () => { 31 | Model({ Counter, Theme }) 32 | const { container } = render( 33 | 34 |