├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── demo └── src │ ├── components │ ├── Calculator.js │ ├── Counter.js │ ├── FriendsList.js │ ├── Items.js │ ├── Notifications.js │ ├── PhotosList.js │ └── Row.js │ ├── index.js │ ├── organisms │ ├── Calculator.js │ ├── Counter.js │ ├── Counter2.js │ ├── Counter3.js │ ├── Counter4.js │ ├── Items.js │ ├── ItemsChoice.js │ └── Social.js │ └── state │ ├── counter.js │ ├── friends.js │ ├── photos.js │ ├── placeholderAPI.js │ └── selection.js ├── nwb.config.js ├── package.json ├── packages └── create-react-organism │ ├── .gitignore │ ├── README.md │ ├── bin │ └── create-react-organism.js │ ├── package.json │ └── yarn.lock ├── src ├── adjustArgs │ └── extractFromDOM.js ├── index.d.ts ├── index.js ├── multi.js └── nextFrame.js ├── tests ├── .eslintrc ├── extractFromDOM-test.js ├── index-test.js └── multi-test.js ├── umd ├── react-organism.js ├── react-organism.min.js └── react-organism.min.js.map └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | /coverage 2 | /demo/dist 3 | /es 4 | /lib 5 | /node_modules 6 | npm-debug.log* 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: node_js 4 | node_js: 5 | - 4 6 | - 6 7 | - 7 8 | - 8 9 | 10 | before_install: 11 | - npm install codecov.io coveralls 12 | 13 | after_success: 14 | - cat ./coverage/lcov.info | ./node_modules/codecov.io/bin/codecov.io.js 15 | - cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js 16 | 17 | branches: 18 | only: 19 | - master 20 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Prerequisites 2 | 3 | [Node.js](http://nodejs.org/) >= v4 must be installed. 4 | 5 | ## Installation 6 | 7 | - Running `npm install` in the components's root directory will install everything you need for development. 8 | 9 | ## Demo Development Server 10 | 11 | - `npm start` will run a development server with the component's demo app at [http://localhost:3000](http://localhost:3000) with hot module reloading. 12 | 13 | ## Running Tests 14 | 15 | - `npm test` will run the tests once. 16 | 17 | - `npm run test:coverage` will run the tests and produce a coverage report in `coverage/`. 18 | 19 | - `npm run test:watch` will run the tests on every change. 20 | 21 | ## Building 22 | 23 | - `npm run build` will build the component for publishing to npm and also bundle the demo app. 24 | 25 | - `npm run clean` will delete built resources. 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Patrick Smith 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Organism 2 | 3 | [![Travis][build-badge]][build] 4 | [![npm package][npm-badge]][npm] 5 | [![Coveralls][coveralls-badge]][coveralls] 6 | 7 | **Dead simple React/Preact state management to bring pure components alive** 8 | 9 | - Supports `async`/`await` and easy loading (e.g. `fetch()`) 10 | - Reload when particular props change 11 | - Animate using generator functions: just `yield` the new state for each frame 12 | - Tiny: 1.69 KB gzipped (3.49 KB uncompressed) 13 | - Embraces the existing functional `setState` while avoiding boilerplate (no writing `this.setState()` or `.bind` again) 14 | - Easy to unit test 15 | 16 | #### Table of contents 17 | 18 | - [Installation](#installation) 19 | - [Demos](#demos) 20 | - [Usage](#usage) 21 | - [Basic](#basic) 22 | - [Using props](#using-props) 23 | - [Async & promises](#async) 24 | - [Handling events](#handling-events) 25 | - [Animation](#animation) 26 | - [Serialization: Local storage](#serialization-local-storage) 27 | - [Separate and reuse state handlers](#separate-and-reuse-state-handlers) 28 | - [Multicelled organisms](#multicelled-organisms) 29 | - [API](#api) 30 | - [`makeOrganism(PureComponent, StateFunctions, options)`](#makeorganismpurecomponent-statefunctions-options) 31 | - [State functions](#state-functions) 32 | - [Argument enhancers](#argument-enhancers) 33 | - [Why instead of Redux?](#why-instead-of-redux) 34 | 35 | ## Installation 36 | 37 | ``` 38 | npm i react-organism --save 39 | ``` 40 | 41 | ## Demos 42 | 43 | - [Animated counter](https://codesandbox.io/s/2vx12v3qmn) 44 | - [Dynamic loading with `import()`](https://codesandbox.io/s/X6mLEwG7W) 45 | - [Live form error validation with Yup](https://codesandbox.io/s/4xQpKRRWx) 46 | - [Multicelled component — using multiple states](https://codesandbox.io/s/Yv7j1xLqM) 47 | - [Todo List](https://codesandbox.io/s/yME5Y3Yz) 48 | - [Inputs, forms, animation, fetch](https://react-organism.now.sh) · [code](https://github.com/BurntCaramel/react-organism/tree/master/demo/src) 49 | - [User Stories Maker](https://codesandbox.io/s/xkZ5ZONl) 50 | - [React Cheat Sheet](https://react-cheat.now.sh/) · [code](https://github.com/BurntCaramel/react-cheat) 51 | 52 | ## Usage 53 | 54 | ### Basic 55 | 56 | ```js 57 | // organisms/Counter.js 58 | import makeOrganism from 'react-organism' 59 | import Counter from './components/Counter' 60 | 61 | export default makeOrganism(Counter, { 62 | initial: () => ({ count: 0 }), 63 | increment: () => ({ count }) => ({ count: count + 1 }), 64 | decrement: () => ({ count }) => ({ count: count - 1 }) 65 | }) 66 | ``` 67 | 68 | ```js 69 | // components/Counter.js 70 | import React, { Component } from 'react' 71 | 72 | export default function Counter({ 73 | count, 74 | handlers: { 75 | increment, 76 | decrement 77 | } 78 | }) { 79 | return ( 80 |
81 |
85 | ) 86 | } 87 | ``` 88 | 89 | ### Using props 90 | 91 | The handlers can easily use props, which are always passed as the first argument 92 | 93 | ```js 94 | // organisms/Counter.js 95 | import makeOrganism from 'react-organism' 96 | import Counter from './components/Counter' 97 | 98 | export default makeOrganism(Counter, { 99 | initial: ({ initialCount = 0 }) => ({ count: initialCount }), 100 | increment: ({ stride = 1 }) => ({ count }) => ({ count: count + stride }), 101 | decrement: ({ stride = 1 }) => ({ count }) => ({ count: count - stride }) 102 | }) 103 | 104 | // Render passing prop: 105 | ``` 106 | 107 | ### Async 108 | 109 | Asynchronous code to load from an API is easy: 110 | 111 | ```js 112 | // components/Items.js 113 | import React, { Component } from 'react' 114 | 115 | export default function Items({ 116 | items, 117 | collectionName, 118 | handlers: { 119 | load 120 | } 121 | }) { 122 | return ( 123 |
124 | { 125 | !!items ? ( 126 | `${items.length} ${collectionName}` 127 | ) : ( 128 | 'Loading…' 129 | ) 130 | } 131 |
132 |
134 |
135 | ) 136 | } 137 | ``` 138 | 139 | ```js 140 | // organisms/Items.js 141 | import makeOrganism from 'react-organism' 142 | import Items from '../components/Items' 143 | 144 | const baseURL = 'https://jsonplaceholder.typicode.com' 145 | const fetchAPI = (path) => fetch(baseURL + path).then(r => r.json()) 146 | 147 | export default makeOrganism(Items, { 148 | initial: () => ({ items: null }), 149 | 150 | load: async ({ path }, prevProps) => { 151 | if (!prevProps || path !== prevProps.path) { 152 | return { items: await fetchAPI(path) } 153 | } 154 | } 155 | }) 156 | ``` 157 | 158 | ```js 159 |
160 | 161 | 162 |
163 | ``` 164 | 165 | ### Handling events 166 | 167 | Handlers can easily accept arguments such as events. 168 | 169 | ```js 170 | // components/Calculator.js 171 | import React, { Component } from 'react' 172 | 173 | export default function Calculator({ 174 | value, 175 | handlers: { 176 | changeValue, 177 | double, 178 | add3, 179 | initial 180 | } 181 | }) { 182 | return ( 183 |
184 | 185 |
189 | ) 190 | } 191 | ``` 192 | 193 | ```js 194 | // organisms/Calculator.js 195 | import makeOrganism from 'react-organism' 196 | import Calculator from '../components/Calculator' 197 | 198 | export default makeOrganism(Calculator, { 199 | initial: ({ initialValue = 0 }) => ({ value: initialValue }), 200 | // Destructure event to get target 201 | changeValue: (props, { target }) => ({ value }) => ({ value: parseInt(target.value, 10) }), 202 | double: () => ({ value }) => ({ value: value * 2 }), 203 | add3: () => ({ value }) => ({ value: value + 3 }) 204 | }) 205 | ``` 206 | 207 | ### Animation 208 | 209 | ```js 210 | import makeOrganism from 'react-organism' 211 | import Counter from '../components/Counter' 212 | 213 | export default makeOrganism(Counter, { 214 | initial: ({ initialCount = 0 }) => ({ count: initialCount }), 215 | increment: function * ({ stride = 20 }) { 216 | while (stride > 0) { 217 | yield ({ count }) => ({ count: count + 1 }) 218 | stride -= 1 219 | } 220 | }, 221 | decrement: function * ({ stride = 20 }) { 222 | while (stride > 0) { 223 | yield ({ count }) => ({ count: count - 1 }) 224 | stride -= 1 225 | } 226 | } 227 | }) 228 | ``` 229 | 230 | ### Automatically extract from `data-` attributes and `` 231 | 232 | Example coming soon 233 | 234 | ### Serialization: Local storage 235 | 236 | ```js 237 | // organisms/Counter.js 238 | import makeOrganism from 'react-organism' 239 | import Counter from '../components/Counter' 240 | 241 | const localStorageKey = 'counter' 242 | 243 | export default makeOrganism(Counter, { 244 | initial: ({ initialCount = 0 }) => ({ count: initialCount }), 245 | load: async (props, prevProps) => { 246 | if (!prevProps) { 247 | // Try commenting out: 248 | /* throw (new Error('Oops!')) */ 249 | 250 | // Load previously stored state, if present 251 | return await JSON.parse(localStorage.getItem(localStorageKey)) 252 | } 253 | }, 254 | increment: ({ stride = 1 }) => ({ count }) => ({ count: count + stride }), 255 | decrement: ({ stride = 1 }) => ({ count }) => ({ count: count - stride }) 256 | }, { 257 | onChange(state) { 258 | // When state changes, save in local storage 259 | localStorage.setItem(localStorageKey, JSON.stringify(state)) 260 | } 261 | }) 262 | ``` 263 | 264 | ### Separate and reuse state handlers 265 | 266 | React Organism supports separating state handlers and the component into their own files. This means state handlers could be reused by multiple smart components. 267 | 268 | Here’s an example of separating state: 269 | 270 | ```js 271 | // state/counter.js 272 | export const initial = () => ({ 273 | count: 0 274 | }) 275 | 276 | export const increment = () => ({ count }) => ({ count: count + 1 }) 277 | export const decrement = () => ({ count }) => ({ count: count - 1 }) 278 | ``` 279 | 280 | ```js 281 | // organisms/Counter.js 282 | import makeOrganism from 'react-organism' 283 | import Counter from './components/Counter' 284 | import * as counterState from './state/counter' 285 | 286 | export default makeOrganism(Counter, counterState) 287 | ``` 288 | 289 | ```js 290 | // App.js 291 | import React from 'react' 292 | import CounterOrganism from './organisms/Counter' 293 | 294 | class App extends React.Component { 295 | render() { 296 | return ( 297 |
298 | 299 |
300 | ) 301 | } 302 | } 303 | ``` 304 | 305 | ### Multicelled Organisms 306 | 307 | Example coming soon. 308 | 309 | 310 | ## API 311 | 312 | ### `makeOrganism(PureComponent, StateFunctions, options?)` 313 | ```js 314 | import makeOrganism from 'react-organism' 315 | ``` 316 | Creates a smart component, rendering using React component `PureComponent`, and managing state using `StateFunctions`. 317 | 318 | #### `PureComponent` 319 | A React component, usually a pure functional component. This component is passed as its props: 320 | 321 | - The props passed to the smart component, combined with 322 | - The current state, combined with 323 | - `handlers` which correspond to each function in `StateFunctions` and are ready to be passed to e.g. `onClick`, `onChange`, etc. 324 | - `loadError?`: Error produced by the `load` handler 325 | - `handlerError?`: Error produced by any other handler 326 | 327 | #### `StateFunctions` 328 | Object with functional handlers. See [state functions below](#state-functions). 329 | 330 | Either pass a object directly with each function, or create a separate file with each handler function `export`ed out, and then bring in using `import * as StateFunctions from '...'`. 331 | 332 | #### `options` 333 | 334 | ##### `adjustArgs?(args: array) => newArgs: array` 335 | 336 | Used to enhance handlers. See [built-in handlers below](#argument-enhancers). 337 | 338 | ##### `onChange?(state)` 339 | 340 | Called after the state has changed, making it ideal for saving the state somewhere (e.g. Local Storage). 341 | 342 | 343 | ### State functions 344 | 345 | Your state is handled by a collection of functions. Each function is pure: they can only rely on the props and state passed to them. Functions return the new state, either immediately or asynchronously. 346 | 347 | Each handler is passed the current props first, followed by the called arguments: 348 | - `(props, event)`: most event handlers, e.g. `onClick`, `onChange` 349 | - `(props, first, second)`: e.g. `handler(first, second)` 350 | - `(props, ...args)`: get all arguments passed 351 | - `(props)`: ignore any arguments 352 | - `()`: ignore props and arguments 353 | 354 | Handlers must return one of the following: 355 | - An object with new state changes, a la React’s `setState(changes)`. 356 | - A function accepting the previous state and current props, and returns the new state, a la React’s `setState((prevState, props) => changes)`. 357 | - A promise resolving to any of the above (object / function), which will then be used to update the state. Uncaught errors are stored in state under the key `handlerError`. Alternatively, your handler can use the `async`/`await` syntax. 358 | - An iterator, such as one made by using a [generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function%2A). Each object passed to `yield` may be one of the above (object / function / promise). 359 | - An array of any of the above (object / function / promise / iterator). 360 | - Or optionally, nothing. 361 | 362 | There are some handlers for special tasks, specifically: 363 | 364 | #### `initial(props) => object` (required) 365 | Return initial state to start off with, a la React’s `initialState`. Passed props. 366 | 367 | #### `load(props: object, prevProps: object?, { handlers: object }) => object | Promise | void` (optional) 368 | Passed the current props and the previous props. Return new state, a Promise returning new state, or nothing. You may also use a generator function (`function * load(props, prevProps)`) and `yield` state changes. 369 | 370 | If this is the first time loaded or if being reloaded, then `prevProps` is `null`. 371 | 372 | Usual pattern is to check for either `prevProps` being `null` or if the prop of interest has changed from its previous value: 373 | ```js 374 | export const load = async ({ id }, prevProps) => { 375 | if (!prevProps || id !== prevProps.id) { 376 | return { item: await loadItem(id) } 377 | } 378 | } 379 | ``` 380 | 381 | Your `load` handler will be called in React’s lifecycle: `componentDidMount` and `componentWillReceiveProps`. 382 | 383 | 384 | ### Argument enhancers 385 | 386 | Handler arguments can be adjusted, to cover many common cases. Pass them to the `adjustArgs` option. The following enhancers are built-in: 387 | 388 | #### `extractFromDOM(args: array) => newArgs: array` 389 | ```js 390 | import extractFromDOM from 'react-organism/lib/adjustArgs/extractFromDOM' 391 | ``` 392 | 393 | Extract values from DOM, specifically: 394 | - For events as the first argument, extracts `value`, `checked`, and `name` from `event.target`. Additionally, if target has `data-` attributes, these will also be extracted in camelCase from its [`dataset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset). Suffixing `data-` attributes with `_number` will convert value to a number (instead of string) using `parseFloat`, and drop the suffix. Handler will receive these extracted values in an object as the first argument, followed by the original arguments. 395 | - For `submit` events, extracts values of `` fields in a `
`. Handler will receive the values keyed by the each input’s `name` attribute, followed by the original arguments. Pass the handler to the `onSubmit` prop of the ``. Form must have `data-extract` attribute present. To clear the form after submit, add `data-reset` to the form. 396 | 397 | 398 | ## Why instead of Redux? 399 | 400 | - Like Redux, separate your state management from rendering 401 | - Unlike Redux, avoid loose strings for identifying actions 402 | - Redux encourages having state in one bundle, whereas dynamic `import()` encourages breaking apps into sections 403 | - Easier to reuse functionality, as action handlers are totally encapsulated 404 | - No ability to reach across to the other side of your state tree 405 | - Encourages composition of components 406 | - Supports `async` and `await` in any action 407 | - Supports generator functions to allow multiple state changes — great for animation 408 | - No `switch` statements 409 | - No boilerplate or additional helper libraries needed 410 | 411 | 412 | [build-badge]: https://img.shields.io/travis/RoyalIcing/react-organism/master.png?style=flat-square 413 | [build]: https://travis-ci.org/RoyalIcing/react-organism 414 | 415 | [npm-badge]: https://img.shields.io/npm/v/react-organism.png?style=flat-square 416 | [npm]: https://www.npmjs.org/package/react-organism 417 | 418 | [coveralls-badge]: https://img.shields.io/coveralls/RoyalIcing/react-organism/master.png?style=flat-square 419 | [coveralls]: https://coveralls.io/github/RoyalIcing/react-organism 420 | -------------------------------------------------------------------------------- /demo/src/components/Calculator.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | 3 | export default function Calculator({ 4 | value, 5 | handlers: { 6 | changeValue, 7 | double, 8 | add3, 9 | initial 10 | } 11 | }) { 12 | return ( 13 |
14 | 15 |
19 | ) 20 | } -------------------------------------------------------------------------------- /demo/src/components/Counter.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | 3 | export default function Counter({ 4 | count, 5 | handlers: { 6 | increment, 7 | decrement, 8 | initial 9 | } 10 | }) { 11 | return ( 12 |
13 |
18 | ) 19 | } -------------------------------------------------------------------------------- /demo/src/components/FriendsList.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | 3 | export default function FriendsList({ 4 | friendsList, 5 | selectedIndex, 6 | onSelectAtIndex, 7 | handlers: { 8 | addRandomFriend 9 | } 10 | }) { 11 | return ( 12 |
13 | { 14 | !!friendsList ? ( 15 | friendsList.map((friend, index) => ( 16 |
23 | Name: { friend.name } 24 |
25 | )) 26 | ) : ( 27 | 'Loading…' 28 | ) 29 | } 30 |
31 |
33 |
34 | ) 35 | } -------------------------------------------------------------------------------- /demo/src/components/Items.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | 3 | export default function Counter({ 4 | items, 5 | collectionName, 6 | handlers: { 7 | load 8 | } 9 | }) { 10 | return ( 11 |
12 | { 13 | !!items ? ( 14 | `${items.length} ${collectionName}` 15 | ) : ( 16 | 'Loading…' 17 | ) 18 | } 19 |
20 |
22 |
23 | ) 24 | } -------------------------------------------------------------------------------- /demo/src/components/Notifications.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | export default function Notifications({ 4 | friends: { 5 | friendsList 6 | }, 7 | photos: { 8 | photosList 9 | } 10 | }) { 11 | return ( 12 |
13 | { `${friendsList.length} friends` } 14 | { ' | ' } 15 | { `${photosList.length} photos` } 16 |
17 | ) 18 | } -------------------------------------------------------------------------------- /demo/src/components/PhotosList.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | 3 | export default function PhotosList({ 4 | photosList, 5 | handlers: { 6 | addRandomPhoto, 7 | addPhoto 8 | } 9 | }) { 10 | return ( 11 |
12 | { 13 | !!photosList ? ( 14 | photosList.map((photo, index) => ( 15 |
16 | 17 |
18 | )) 19 | ) : ( 20 | 'Loading…' 21 | ) 22 | } 23 |
24 | 25 | 29 |
32 |
33 |
35 |
36 | ) 37 | } -------------------------------------------------------------------------------- /demo/src/components/Row.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | const style = { 4 | display: 'flex', 5 | flexDirection: 'row' 6 | } 7 | 8 | export default function Row({ 9 | children 10 | }) { 11 | return ( 12 |
13 | ) 14 | } -------------------------------------------------------------------------------- /demo/src/index.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import { render } from 'react-dom' 3 | 4 | import CounterOrganism from './organisms/Counter' 5 | import Counter2Organism from './organisms/Counter2' 6 | import Counter3Organism from './organisms/Counter3' 7 | import Counter4Organism from './organisms/Counter4' 8 | import ItemsOrganism from './organisms/Items' 9 | import ItemsChoiceOrganism from './organisms/ItemsChoice' 10 | import CalculatorOrganism from './organisms/Calculator' 11 | import SocialOrganism from './organisms/Social' 12 | 13 | class Demo extends Component { 14 | render() { 15 | return
16 |

react-organism

17 |

Simple counter:

18 | 19 |
20 |

Using props to customize:

21 | 22 |
23 |

Local storage (change and reload page):

24 | 25 |
26 |

Async animated:

27 | 28 |
29 |

Load data from API:

30 | 31 |
32 | 33 |
34 | 35 |
36 |

Handling prop changes:

37 | 38 |
39 |

Event handlers with calculator:

40 | 41 |
42 |

Multi-celled organism

43 | 44 | 45 | 85 |
86 | } 87 | } 88 | 89 | render(, document.querySelector('#demo')) 90 | -------------------------------------------------------------------------------- /demo/src/organisms/Calculator.js: -------------------------------------------------------------------------------- 1 | import makeOrganism from '../../../src' 2 | import extractFromDOM from '../../../src/adjustArgs/extractFromDOM' 3 | import Calculator from '../components/Calculator' 4 | 5 | export default makeOrganism(Calculator, { 6 | initial: ({ initialValue = 0 }) => ({ value: initialValue }), 7 | changeValue: (props, { value }) => ({ value: parseInt(value, 10) || '' }), 8 | // Or more robust number input handling with fallback to previous value: 9 | // changeValue: (props, { target: { value: newValue } }) => ({ value: previousValue }) => ({ 10 | // value: newValue && (parseInt(newValue, 10) || previousValue) 11 | // }), 12 | double: () => ({ value }) => ({ value: (value || 0) * 2 }), 13 | add3: () => ({ value }) => ({ value: (value || 0) + 3 }) 14 | }, { 15 | adjustArgs: extractFromDOM 16 | }) 17 | -------------------------------------------------------------------------------- /demo/src/organisms/Counter.js: -------------------------------------------------------------------------------- 1 | import makeOrganism from '../../../src' 2 | import * as counterState from '../state/counter' 3 | import Counter from '../components/Counter' 4 | 5 | //export default makeOrganism(Counter, counterState) 6 | 7 | export default makeOrganism(Counter, { 8 | initial: () => ({ count: 0 }), 9 | increment: () => ({ count }) => ({ count: count + 1 }), 10 | decrement: () => ({ count }) => ({ count: count - 1 }) 11 | }) 12 | -------------------------------------------------------------------------------- /demo/src/organisms/Counter2.js: -------------------------------------------------------------------------------- 1 | import makeOrganism from '../../../src' 2 | import Counter from '../components/Counter' 3 | 4 | export default makeOrganism(Counter, { 5 | initial: ({ initialCount = 0 }) => ({ count: initialCount }), 6 | increment: () => ({ count }, { stride = 1 }) => ({ count: count + stride }), 7 | decrement: () => ({ count }, { stride = 1 }) => ({ count: count - stride }) 8 | }) 9 | -------------------------------------------------------------------------------- /demo/src/organisms/Counter3.js: -------------------------------------------------------------------------------- 1 | import makeOrganism from '../../../src' 2 | import Counter from '../components/Counter' 3 | 4 | const localStorageKey = 'counter3' 5 | 6 | export default makeOrganism(Counter, { 7 | initial: ({ initialCount = 13 }) => ({ count: initialCount }), 8 | load: async (props, prevProps) => { 9 | if (!prevProps) { 10 | // Try commenting out: 11 | /* throw (new Error('Oops!')) */ 12 | 13 | // Load previously stored state, if present 14 | return await JSON.parse(localStorage.getItem(localStorageKey)) 15 | } 16 | }, 17 | increment: ({ stride = 1 }) => ({ count }) => ({ count: count + stride }), 18 | decrement: ({ stride = 1 }) => ({ count }) => ({ count: count - stride }) 19 | }, { 20 | onChange(state) { 21 | // When state changes, save in local storage 22 | localStorage.setItem(localStorageKey, JSON.stringify(state)) 23 | } 24 | }) 25 | -------------------------------------------------------------------------------- /demo/src/organisms/Counter4.js: -------------------------------------------------------------------------------- 1 | import makeOrganism from '../../../src' 2 | import Counter from '../components/Counter' 3 | 4 | export default makeOrganism(Counter, { 5 | initial: ({ initialCount = 0 }) => ({ count: initialCount }), 6 | increment: function * ({ stride = 20 }) { 7 | while (stride > 0) { 8 | yield ({ count }) => ({ count: count + 1 }) 9 | stride -= 1 10 | } 11 | }, 12 | decrement: function * ({ stride = 20 }) { 13 | while (stride > 0) { 14 | yield ({ count }) => ({ count: count - 1 }) 15 | stride -= 1 16 | } 17 | } 18 | }) 19 | -------------------------------------------------------------------------------- /demo/src/organisms/Items.js: -------------------------------------------------------------------------------- 1 | import makeOrganism from '../../../src' 2 | import * as loadItemsState from '../state/placeholderAPI' 3 | import Items from '../components/Items' 4 | 5 | // export default makeOrganism(Items, loadItemsState) 6 | 7 | const baseURL = 'https://jsonplaceholder.typicode.com' 8 | const fetchAPI = (path) => fetch(baseURL + path).then(r => r.json()) 9 | 10 | export default makeOrganism(Items, { 11 | initial: () => ({ items: null }), 12 | 13 | load: function * ({ path }, prevProps) { 14 | if (!prevProps || path !== prevProps.path) { 15 | yield { items: null } // Clear so 'loading…' text appears 16 | yield fetchAPI(path).then(items => ({ items })) 17 | } 18 | } 19 | }) 20 | -------------------------------------------------------------------------------- /demo/src/organisms/ItemsChoice.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import makeOrganism from '../../../src' 3 | import ItemsOrganism from './Items' 4 | 5 | export default makeOrganism(({ 6 | collection, 7 | handlers: { 8 | selectPosts, 9 | selectPhotos, 10 | selectTodos 11 | } 12 | }) => ( 13 |
14 |
15 | 16 | 17 | 18 |
19 | 20 |
21 | ), { 22 | initial: () => ({ collection: 'posts' }), 23 | selectPosts: () => ({ collection: 'posts' }), 24 | selectPhotos: () => ({ collection: 'photos' }), 25 | selectTodos: () => ({ collection: 'todos' }) 26 | }) -------------------------------------------------------------------------------- /demo/src/organisms/Social.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import makeMultiCelledOrganism from '../../../src/multi' 3 | import extractFromDOM from '../../../src/adjustArgs/extractFromDOM' 4 | import PhotosList from '../components/PhotosList' 5 | import FriendsList from '../components/FriendsList' 6 | import Notifications from '../components/Notifications' 7 | import Row from '../components/Row' 8 | 9 | import * as friends from '../state/friends' 10 | import * as photos from '../state/photos' 11 | import * as selection from '../state/selection' 12 | 13 | const styles = { 14 | light: { 15 | color: '#111', 16 | backgroundColor: '#f6f6f6' 17 | }, 18 | dark: { 19 | color: '#f6f6f6', 20 | backgroundColor: '#222' 21 | } 22 | } 23 | 24 | function Social({ 25 | darkMode = false, 26 | cells 27 | }) { 28 | return ( 29 |
30 | 31 | 36 | 41 |
42 | ) 43 | } 44 | 45 | export default makeMultiCelledOrganism(Social, { 46 | friends, 47 | photos, 48 | selection 49 | }, { 50 | adjustArgs: extractFromDOM 51 | }) -------------------------------------------------------------------------------- /demo/src/state/counter.js: -------------------------------------------------------------------------------- 1 | export const initial = () => ({ count: 0 }) 2 | 3 | export const increment = () => ({ count }) => ({ count: count + 1 }) 4 | export const decrement = () => ({ count }) => ({ count: count - 1 }) -------------------------------------------------------------------------------- /demo/src/state/friends.js: -------------------------------------------------------------------------------- 1 | export const initial = () => ({ 2 | friendsList: [] 3 | }) 4 | 5 | const convertUserToFriend = (user) => ({ 6 | name: `${user.first} ${user.last}` 7 | }) 8 | 9 | const fetchRandomFriends = () => 10 | fetch('https://randomapi.com/api/6de6abfedb24f889e0b5f675edc50deb?fmt=raw&sole') 11 | .then(res => res.json()) 12 | .then(users => users.slice(0, 10)) 13 | .then(users => users.map(convertUserToFriend)) 14 | 15 | export const load = async (props, prevProps) => { 16 | if (!prevProps) { 17 | const newFriends = await fetchRandomFriends() 18 | return ({ friendsList }) => ({ friendsList: friendsList.concat(newFriends) }) 19 | } 20 | } 21 | 22 | export const addFriend = (props, { name }) => ({ friendsList }) => ({ friendsList: friendsList.concat({ name }) }) 23 | 24 | export const addRandomFriend = async ({ handlers }) => { 25 | const [ newFriend ] = await fetchRandomFriends() 26 | handlers.addFriend(newFriend) 27 | } -------------------------------------------------------------------------------- /demo/src/state/photos.js: -------------------------------------------------------------------------------- 1 | export const initial = () => ({ 2 | photosList: [] 3 | }) 4 | 5 | const fetchRandomPhotoURL = () => 6 | fetch( 7 | 'https://source.unsplash.com/random/800x600', 8 | { method: 'HEAD', cache: 'no-cache' } 9 | ) 10 | .then(res => res.url) 11 | 12 | export const load = async (props, prevProps) => { 13 | if (!prevProps) { 14 | const url = await fetchRandomPhotoURL() 15 | return ({ photosList }) => ({ photosList: photosList.concat({ url }) }) 16 | } 17 | } 18 | 19 | export const addPhoto = (props, { url }) => ({ photosList }) => ({ photosList: photosList.concat({ url }) }) 20 | 21 | export const addRandomPhoto = async (props) => { 22 | const url = await fetchRandomPhotoURL() 23 | return addPhoto({}, { url }) 24 | } -------------------------------------------------------------------------------- /demo/src/state/placeholderAPI.js: -------------------------------------------------------------------------------- 1 | const baseURL = 'https://jsonplaceholder.typicode.com' 2 | const fetchAPI = (path) => fetch(baseURL + path).then(r => r.json()) 3 | 4 | export const initial = () => ({ items: null }) 5 | 6 | export const load = async ({ path }, prevProps) => { 7 | if (!prevProps || path !== prevProps.path) { 8 | console.log('load', path) 9 | return { items: await fetchAPI(path) } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /demo/src/state/selection.js: -------------------------------------------------------------------------------- 1 | export const initial = () => ({ 2 | selectedFriendIndex: null, 3 | selectedPhotoIndex: null 4 | }) 5 | 6 | export const selectFriendAtIndex = (props, { index }) => ({ selectedFriendIndex: index }) 7 | export const selectPhotoAtIndex = (props, { index }) => ({ selectedPhotoIndex: index }) 8 | -------------------------------------------------------------------------------- /nwb.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | type: 'react-component', 3 | webpack: { 4 | hoisting: true 5 | }, 6 | npm: { 7 | esModules: true, 8 | umd: { 9 | global: 'makeOrganism', 10 | externals: { 11 | 'react': 'React' 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-organism", 3 | "version": "0.3.8", 4 | "description": "Separate React state in a dead simple functional way", 5 | "main": "lib/index.js", 6 | "module": "es/index.js", 7 | "types": "src/index.d.ts", 8 | "files": [ 9 | "css", 10 | "es", 11 | "lib", 12 | "umd" 13 | ], 14 | "scripts": { 15 | "build": "nwb build-react-component", 16 | "clean": "nwb clean-module && nwb clean-demo", 17 | "dev": "nwb serve-react-demo", 18 | "test": "nwb test-react", 19 | "test:coverage": "nwb test-react --coverage", 20 | "test:watch": "nwb test-react --server", 21 | "now:deploy": "yarn run build && cd demo/dist && now deploy", 22 | "explore-bundle": "source-map-explorer", 23 | "prepublishOnly": "npm run test && npm run build" 24 | }, 25 | "dependencies": { 26 | "awareness": "^1.1.4" 27 | }, 28 | "peerDependencies": { 29 | "react": "^15.0.0-0 || ^16.0.0-0" 30 | }, 31 | "devDependencies": { 32 | "nwb": "^0.21.5", 33 | "react": "^16.0.0-0", 34 | "react-dom": "^16.0.0-0", 35 | "source-map-explorer": "^1.3.3" 36 | }, 37 | "author": "", 38 | "homepage": "", 39 | "license": "MIT", 40 | "repository": "", 41 | "keywords": [ 42 | "react-component" 43 | ] 44 | } 45 | -------------------------------------------------------------------------------- /packages/create-react-organism/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /packages/create-react-organism/README.md: -------------------------------------------------------------------------------- 1 | # create-react-organism 2 | 3 | Easily create [react-organism](https://github.com/RoyalIcing/react-organism) smart components. 4 | 5 | ## Usage 6 | 7 | ```sh 8 | yarn create react-organism CustomName 9 | 10 | # or 11 | 12 | npm i -g create-react-organism 13 | create-react-organism CustomName 14 | ``` 15 | 16 | Creates an **organisms** directory in your project, and a directory for your organism inside there: **[/src]/organisms/CustomName/** 17 | 18 | Three files are created inside: 19 | - **[CustomName].js:** a pure React component that renders the given state as props, as well as call action handlers defined in **state.js** 20 | - **state.js:** a list of exported functions that handle the progression of state, from its `initial` form, to `load` data in asynchronously, to other action handlers that are called in response to events (e.g. onClick, onChange, etc). 21 | - **index.js:** connects the pure component and state together and exports it for easy use. 22 | 23 | To use the organism, simply import it: 24 | 25 | ```javascript 26 | // pages/example.js 27 | import CustomName from '../organisms/CustomName' 28 | 29 | export default () => ( 30 |
31 | 32 |
33 | ) 34 | ``` -------------------------------------------------------------------------------- /packages/create-react-organism/bin/create-react-organism.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const Path = require('path') 4 | const FS = require('fs') 5 | const Spawn = require('cross-spawn') 6 | const { resolve, coroutine, runNode } = require('creed') 7 | const _ = require('lodash') 8 | 9 | const accessibleFile = (path) => runNode(FS.access, path).map(() => path).catch(() => null) 10 | 11 | const ensureDir = (path) => runNode(FS.mkdir, path).catch(e => { 12 | if (e.code === 'EEXIST') { 13 | return 14 | } 15 | 16 | throw e 17 | }) 18 | 19 | const installPackage = coroutine(function * installPackage(projectPath, packageName) { 20 | const appPackage = require(Path.join(projectPath, 'package.json')) 21 | const dependencies = appPackage.dependencies || {} 22 | const hasInstalled = !!dependencies[packageName] 23 | if (hasInstalled) { 24 | return 25 | } 26 | 27 | const useYarn = !!(yield accessibleFile(Path.join(projectPath, 'yarn.lock'))) 28 | const command = useYarn ? 'yarnpkg' : 'npm' 29 | let args = useYarn ? ['add'] : ['install', '--save'] 30 | args.push(packageName) 31 | const proc = Spawn.sync(command, args, { stdio: 'inherit' }) 32 | if (proc.status !== 0) { 33 | throw new Error(`\`${command} ${args.join(' ')}\` failed with status ${proc.status}`) 34 | } 35 | }) 36 | 37 | function * run([ inputName, ...args ]) { 38 | //const fileName = _.kebabCase(inputName) 39 | const componentName = _.upperFirst(_.camelCase(inputName)) 40 | 41 | let projectPath = process.cwd() 42 | let srcPath = yield accessibleFile(Path.resolve(projectPath, 'src')) 43 | const codePath = srcPath || projectPath 44 | 45 | // Add react-organism dependency 46 | yield installPackage(projectPath, 'react-organism') 47 | 48 | // organisms/ 49 | const organismsDirPath = Path.resolve(codePath, 'organisms') 50 | yield ensureDir(organismsDirPath) 51 | 52 | // organisms/:fileName 53 | const organismPath = Path.join(organismsDirPath, componentName) 54 | yield ensureDir(organismPath) 55 | 56 | // organisms/:fileName/component.js 57 | yield runNode(FS.writeFile, Path.join(organismPath, 'component.js'), makeComponentJS(componentName)) 58 | // organisms/:fileName/state.js 59 | yield runNode(FS.writeFile, Path.join(organismPath, 'state.js'), makeStateJS(componentName)) 60 | // organisms/:fileName/index.js 61 | yield runNode(FS.writeFile, Path.join(organismPath, 'index.js'), makeIndexJS(componentName)) 62 | } 63 | 64 | 65 | function makeStateJS(componentName) { 66 | return ` 67 | export const initial = () => ({ 68 | // TODO: initial state properties 69 | }) 70 | 71 | export const example = (props, ...args) => (prevState) => { 72 | // TODO: return changed state 73 | return prevState 74 | } 75 | `.trim() 76 | } 77 | 78 | 79 | function makeComponentJS(componentName) { 80 | return ` 81 | import React from 'react' 82 | 83 | export default function ${componentName}({ 84 | // TODO: props 85 | handlers: { 86 | example 87 | // TODO: state handlers 88 | } 89 | }) { 90 | return ( 91 |
92 |
93 | ) 94 | } 95 | `.trim() 96 | } 97 | 98 | function makeIndexJS(componentName) { 99 | return ` 100 | import makeOrganism from 'react-organism' 101 | import ${componentName} from './component' 102 | import * as state from './state' 103 | 104 | export default makeOrganism(${componentName}, state) 105 | `.trim() 106 | } 107 | 108 | coroutine(run)(process.argv.slice(2)) 109 | .catch(error => { 110 | console.error(error.message) 111 | }) 112 | -------------------------------------------------------------------------------- /packages/create-react-organism/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "create-react-organism", 3 | "version": "0.2.0", 4 | "description": "Tool to easily create react-organism smart components", 5 | "engines": { 6 | "node": ">=6" 7 | }, 8 | "bin": { 9 | "create-react-organism": "./bin/create-react-organism.js" 10 | }, 11 | "main": "index.js", 12 | "repository": "https://github.com/RoyalIcing/react-organism", 13 | "author": "Patrick Smith ", 14 | "license": "MIT", 15 | "dependencies": { 16 | "creed": "^1.2.1", 17 | "cross-spawn": "^5.1.0", 18 | "lodash": "^4.17.4" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /packages/create-react-organism/yarn.lock: -------------------------------------------------------------------------------- 1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. 2 | # yarn lockfile v1 3 | 4 | 5 | creed@^1.2.1: 6 | version "1.2.1" 7 | resolved "https://registry.yarnpkg.com/creed/-/creed-1.2.1.tgz#94e2420c0538e38b701b1dce893d2cda73fe18fd" 8 | 9 | cross-spawn@^5.1.0: 10 | version "5.1.0" 11 | resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-5.1.0.tgz#e8bd0efee58fcff6f8f94510a0a554bbfa235449" 12 | dependencies: 13 | lru-cache "^4.0.1" 14 | shebang-command "^1.2.0" 15 | which "^1.2.9" 16 | 17 | isexe@^2.0.0: 18 | version "2.0.0" 19 | resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" 20 | 21 | lodash@^4.17.4: 22 | version "4.17.4" 23 | resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.4.tgz#78203a4d1c328ae1d86dca6460e369b57f4055ae" 24 | 25 | lru-cache@^4.0.1: 26 | version "4.1.1" 27 | resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.1.tgz#622e32e82488b49279114a4f9ecf45e7cd6bba55" 28 | dependencies: 29 | pseudomap "^1.0.2" 30 | yallist "^2.1.2" 31 | 32 | pseudomap@^1.0.2: 33 | version "1.0.2" 34 | resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3" 35 | 36 | shebang-command@^1.2.0: 37 | version "1.2.0" 38 | resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" 39 | dependencies: 40 | shebang-regex "^1.0.0" 41 | 42 | shebang-regex@^1.0.0: 43 | version "1.0.0" 44 | resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" 45 | 46 | which@^1.2.9: 47 | version "1.2.14" 48 | resolved "https://registry.yarnpkg.com/which/-/which-1.2.14.tgz#9a87c4378f03e827cecaf1acdf56c736c01c14e5" 49 | dependencies: 50 | isexe "^2.0.0" 51 | 52 | yallist@^2.1.2: 53 | version "2.1.2" 54 | resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52" 55 | -------------------------------------------------------------------------------- /src/adjustArgs/extractFromDOM.js: -------------------------------------------------------------------------------- 1 | import extractValuesFromDOMEvent from 'awareness/lib/extractValuesFromDOMEvent' 2 | 3 | export default function extractFromDOM(args) { 4 | if (args[0]) { 5 | const values = extractValuesFromDOMEvent(args[0]) 6 | 7 | // Place extracted dataset values first, followed by original arguments 8 | args = [values].concat(args) 9 | } 10 | 11 | return args 12 | } -------------------------------------------------------------------------------- /src/index.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'react-organism' { 2 | import React from 'react' 3 | 4 | export interface ReceiverProps { 5 | handlers: HandlersOut 6 | } 7 | 8 | function makeOrganism( 9 | Pure: 10 | | React.ComponentClass> 11 | | React.StatelessComponent>, 12 | handlersIn: HandlersIn, 13 | options?: { 14 | onChange: (newState: State) => {} 15 | adjustArgs: (args: any[]) => any[] 16 | } 17 | ): React.ComponentClass 18 | 19 | export default makeOrganism 20 | } 21 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React, { PureComponent } from 'react' 2 | import makeAwareness from 'awareness' 3 | 4 | // Returns a new stateful component, given the specified state handlers and a pure component to render with 5 | export default ( 6 | Pure, 7 | handlersIn, 8 | { 9 | onChange, 10 | adjustArgs 11 | } = {} 12 | ) => class Organism extends PureComponent { 13 | static initialStateForProps(props) { 14 | return handlersIn.initial(props) 15 | } 16 | 17 | get currentState() { 18 | return this.props.getState ? this.props.getState() : this.state 19 | } 20 | 21 | alterState = (stateChanger) => { 22 | // Can either be a plain object or a callback to transform the existing state 23 | (this.props.setState || this.setState).call( 24 | this, 25 | stateChanger, 26 | // Call onChange once updated with current version of state 27 | onChange ? () => { onChange(this.currentState) } : undefined 28 | ) 29 | } 30 | 31 | awareness = makeAwareness(this.alterState, handlersIn, { 32 | getProps: () => this.props, 33 | adjustArgs 34 | }) 35 | 36 | state = this.awareness.state 37 | 38 | componentDidMount() { 39 | this.awareness.loadAsync(this.props, null, this.currentState) 40 | } 41 | 42 | componentDidUpdate(prevProps, prevState) { 43 | this.awareness.loadAsync(this.props, prevProps, this.currentState) 44 | } 45 | 46 | render() { 47 | // Render the pure component, passing both props and state, plus handlers bundled together 48 | return 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/multi.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import makeAwareness from 'awareness' 3 | import nextFrame from './nextFrame' 4 | 5 | function cellStateChangerCatchingError(cellKey, stateChanger, errorKey) { 6 | return (prevState, props) => { 7 | let cellChanges = {} 8 | // Check if stateChanger is a function 9 | if (typeof(stateChanger) === typeof(stateChanger.call)) { 10 | try { 11 | // Call state changer 12 | cellChanges = stateChanger(prevState[cellKey], props) 13 | } 14 | // State changer may throw 15 | catch (error) { 16 | // Store error in state 17 | return { [errorKey]: error } 18 | } 19 | } 20 | // Else just an object with changes 21 | else { 22 | cellChanges = stateChanger 23 | } 24 | return { 25 | [cellKey]: Object.assign({}, prevState[cellKey], cellChanges) 26 | } 27 | } 28 | } 29 | 30 | function processStateChanger(changeState, stateChanger, storeError) { 31 | if (!stateChanger) { 32 | return; 33 | } 34 | 35 | // Check if thenable (i.e. a Promise) 36 | if (typeof stateChanger.then === typeof Object.assign) { 37 | return stateChanger.then(stateChanger => ( 38 | stateChanger && changeState(stateChanger) 39 | )) 40 | .catch(storeError) 41 | } 42 | // Check if iterator 43 | else if (typeof stateChanger.next === typeof Object.assign) { 44 | return processIterator(changeState, stateChanger, storeError) 45 | } 46 | // Otherwise, change state immediately 47 | // Required for things like