├── .babelrc ├── .editorconfig ├── .gitignore ├── .prettierrc ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── inspect.js ├── package.json ├── rollup.config.js ├── src ├── __tests__ │ ├── __snapshots__ │ │ ├── provider.test.js.snap │ │ └── state.test.js.snap │ ├── index.test.js │ ├── provider.test.js │ └── state.test.js ├── index.js ├── provider.js └── state.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["env", "react"] 3 | } 4 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | [*] 3 | # Change these settings to your own preference 4 | indent_style = space 5 | indent_size = 2 6 | # We recommend you to keep these unchanged 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | [*.md] 12 | trim_trailing_whitespace = false 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | npm-debug.log 4 | .DS_Store 5 | coverage 6 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "jsxBracketSameLine": true 5 | } 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 8 4 | notifications: 5 | email: false 6 | script: 7 | - npm run test 8 | after_success: 9 | - npm install -g codecov 10 | - codecov 11 | branches: 12 | only: 13 | - master 14 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | 6 | ## [2.0.4](https://github.com/vesparny/statty/compare/v2.0.2...v2.0.4) (2018-04-11) 7 | 8 | 9 | ### Bug Fixes 10 | 11 | * Improved memory usage for state management ([#18](https://github.com/vesparny/statty/issues/18)) ([50fd5d7](https://github.com/vesparny/statty/commit/50fd5d7)) 12 | * not throwing errors when multiple updates happen ([ea9a92b](https://github.com/vesparny/statty/commit/ea9a92b)) 13 | 14 | 15 | 16 | 17 | ## [2.0.3](https://github.com/vesparny/statty/compare/v2.0.2...v2.0.3) (2017-10-15) 18 | 19 | 20 | ### Bug Fixes 21 | 22 | * setState when needed in case children update state in cWM/cDM closes #15 (#16) ([5ebe2c2](https://github.com/vesparny/statty/commit/5ebe2c2)), closes [#15](https://github.com/vesparny/statty/issues/15) [#16](https://github.com/vesparny/statty/issues/16) 23 | 24 | 25 | 26 | 27 | ## [2.0.2](https://github.com/vesparny/statty/compare/v2.0.1...v2.0.2) (2017-10-03) 28 | 29 | 30 | ### Bug Fixes 31 | 32 | * remove useless typeof comparison ([87f3f6a](https://github.com/vesparny/statty/commit/87f3f6a)) 33 | 34 | 35 | 36 | 37 | ## [2.0.1](https://github.com/vesparny/statty/compare/v2.0.0...v2.0.1) (2017-10-03) 38 | 39 | 40 | ### Bug Fixes 41 | 42 | * if selectors returns undefined or null always rerender ([dc7b8b6](https://github.com/vesparny/statty/commit/dc7b8b6)) 43 | 44 | 45 | 46 | 47 | # [2.0.0](https://github.com/vesparny/statty/compare/v1.0.0...v2.0.0) (2017-10-03) 48 | 49 | 50 | ### Bug Fixes 51 | 52 | * throws if updaters invoke other updaters ([67e8a26](https://github.com/vesparny/statty/commit/67e8a26)) 53 | 54 | 55 | ### Chores 56 | 57 | * do not use xtend anymore ([08085de](https://github.com/vesparny/statty/commit/08085de)) 58 | 59 | 60 | ### Performance Improvements 61 | 62 | * improve performance with nested subscription by re-rendering only if necessary ([3e473fa](https://github.com/vesparny/statty/commit/3e473fa)) 63 | 64 | 65 | ### BREAKING CHANGES 66 | 67 | * updaters MUST return a complete new state, without 68 | mutating the old one 69 | 70 | 71 | 72 | 73 | # 1.0.0 (2017-09-25) 74 | 75 | 76 | ### Features 77 | 78 | * add inspect ([97b6368](https://github.com/vesparny/statty/commit/97b6368)) 79 | * initial version ([ad8e5ba](https://github.com/vesparny/statty/commit/ad8e5ba)) 80 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017-present Alessandro Arnodo 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 | # statty 2 | 3 | > A tiny and unobtrusive state management library for React and Preact apps 4 | 5 | [![Travis](https://img.shields.io/travis/vesparny/statty.svg)](https://travis-ci.org/vesparny/statty) 6 | [![Code Coverage](https://img.shields.io/codecov/c/github/vesparny/statty.svg?style=flat-square)](https://codecov.io/github/vesparny/statty) 7 | [![David](https://img.shields.io/david/vesparny/statty.svg)](https://david-dm.org/vesparny/statty) 8 | [![npm](https://img.shields.io/npm/v/statty.svg)](https://www.npmjs.com/package/statty) 9 | [![npm](https://img.shields.io/npm/dm/statty.svg)](https://npm-stat.com/charts.html?package=statty&from=2017-05-19) 10 | [![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) 11 | [![MIT License](https://img.shields.io/npm/l/statty.svg?style=flat-square)](https://github.com/vesparny/statty/blob/master/LICENSE) 12 | 13 | The current size of `statty/dist/statty.umd.min.js` is: 14 | 15 | [![gzip size](http://img.badgesize.io/https://unpkg.com/statty/dist/statty.umd.min.js?compression=gzip&label=gzip%20size&style=flat-square)](https://unpkg.com/statty/dist/) 16 | 17 | ## The problem 18 | 19 | Most of the time, I see colleagues starting React projects setting up Redux + a bunch of middlewares and store enhancers by default, regardless of the project nature. 20 | 21 | Despite Redux being awesome, [it's not always needed](https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367) and it may slow down the process of onboarding new developers, especially if they are new to the React ecosystem (I have often seen colleagues being stuck for hours trying to understand what was the proper way to submit a simple form). 22 | 23 | React already comes with a built-in state management mechanism, `setState()`. Local component state is just fine in most of the cases. 24 | 25 | In real world apps we often have app state, and sometimes it becomes annoying to pass it down the entire component tree, along with callbacks to update it, via props. 26 | 27 | ## This solution 28 | 29 | `statty` is meant to manage app-wide state and can be thought of as a simplified version of Redux. 30 | 31 | It [safely](https://medium.com/@mweststrate/how-to-safely-use-react-context-b7e343eff076) leverages context to expose application state to children, along with a function to update it when needed. 32 | 33 | The update function acts like Redux dispatch, but instead of an action, it takes an `updater` function as a parameter that returns the new state. 34 | 35 | This way it's easy to write testable updaters and to organize them as you prefer, without having to write boilerplate code. 36 | 37 | ## Table of Contents 38 | 39 | - [Installation](#installation) 40 | - [Usage](#usage) 41 | - [API](#api) 42 | - [Examples](#examples) 43 | - [Inspiration](#inspiration) 44 | - [LICENSE](#license) 45 | 46 | ## Installation 47 | 48 | This project uses [node](http://nodejs.org) and [npm](https://npmjs.com). Check them out if you don't have them locally installed. 49 | 50 | ```sh 51 | $ npm i statty 52 | ``` 53 | 54 | Then with a module bundler like [rollup](http://rollupjs.org/) or [webpack](https://webpack.js.org/), use as you would anything else: 55 | 56 | ```javascript 57 | // using ES6 modules 58 | import statty from 'statty' 59 | 60 | // using CommonJS modules 61 | var statty = require('statty') 62 | ``` 63 | 64 | The [UMD](https://github.com/umdjs/umd) build is also available on [unpkg](https://unpkg.com): 65 | 66 | ```html 67 | 68 | ``` 69 | 70 | You can find the library on `window.statty`. 71 | 72 | ## Usage 73 | 74 | ```jsx 75 | // https://codesandbox.io/s/rzpxx0w34 76 | import React from 'react' 77 | import { render } from 'react-dom' 78 | import { Provider, State } from 'statty' 79 | import inspect from 'statty/inspect' 80 | 81 | // selector is a function that returns a slice of the state 82 | // if not specified it defaults to f => f 83 | const selector = state => ({ count: state.count }) 84 | 85 | // updaters 86 | 87 | // updaters MUST be pure and return a complete new state, 88 | // like Redux reducers 89 | const onDecrement = state => 90 | Object.assign({}, state, { count: state.count - 1 }) 91 | 92 | const onIncrement = state => 93 | Object.assign({}, state, { count: state.count + 1 }) 94 | 95 | // Counter uses a component to access the state 96 | // and the update function used to execute state mutations 97 | const Counter = () => ( 98 | ( 101 |
102 | Clicked: {count} times 103 | {' '} 104 | {' '} 105 |
106 | )} 107 | /> 108 | ) 109 | 110 | // initial state 111 | const initialState = { 112 | count: 0 113 | } 114 | 115 | // The component is supposed to be placed at the top 116 | // of your application. It accepts the initial state and an inspect function 117 | // useful to log state mutatations during development 118 | // (check your dev tools to see it in action) 119 | const App = () => ( 120 | 121 | 122 | 123 | ) 124 | 125 | render(, document.getElementById('root')) 126 | 127 | 128 | ``` 129 | 130 | The `` component is used to share the state via context. 131 | The `` component takes 2 props: 132 | 133 | * `select` is a function that takes the entire state, and returns only the part of it that the children will need 134 | * `render` is a [render prop](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce) that takes the `selected state` and the `update` function as parameters, giving the user full control on what to render based on props and state. 135 | 136 | State updates happen via special `updater` functions that take the old state as a parameter and return the new state, triggering a rerender. 137 | 138 | An updater function may return the slice of the state that changed or an entire new state. In the first case the new slice will be shallowly merged with old state. 139 | 140 | ## API 141 | 142 | ### `` 143 | 144 | Makes state available to children `` 145 | 146 | #### props 147 | 148 | ##### `state` 149 | 150 | > `object` | required 151 | 152 | The initial state 153 | 154 | ##### `inspect` 155 | 156 | > `function(oldState: object, newState: object, updaterFn: function)` 157 | 158 | Use the inspect prop during development to track state changes. 159 | 160 | `statty` comes with a default logger inspired by redux-logger. 161 | 162 | ```jsx 163 | 167 | ``` 168 | 169 | ### `` 170 | 171 | Connects children to state changes, and provides them with the `update` function 172 | 173 | #### props 174 | 175 | ##### `select` 176 | 177 | > `function(state: object) | defaults to s => s | returns object` 178 | 179 | Selects the slice of the state needed by the children components. 180 | 181 | ##### `render` 182 | 183 | > `function(state: object, update: function)` | required 184 | 185 | A render prop that takes the state returned by the `selector` and an `update` function. 186 | 187 | 188 | ## Examples 189 | 190 | Examples exist on [codesandbox.io](https://codesandbox.io/search?refinementList%5Btags%5D%5B0%5D=statty%3Aexample&page=1): 191 | 192 | - [Counter](https://codesandbox.io/s/rzpxx0w34) 193 | - [Preact example without Preact compat (codepen)](https://codepen.io/vesparny/pen/gGgyVN) 194 | - [Counter with reducer](https://codesandbox.io/s/jp9zj98l5w) 195 | - [Counter with async interactions](https://codesandbox.io/s/kxkp47o597) 196 | - [Wikipedia searchbox with RxJS and Ramda](https://codesandbox.io/s/7wx3v8jqqq) 197 | - [Wikipedia searchbox + Downshift integration](https://codesandbox.io/s/pymj32z5kj) 198 | - [Tree-view example](https://codesandbox.io/s/3y146z2qop) (shows how to get good performance with nested subscriptions). 199 | 200 | If you would like to add an example, follow these steps: 201 | 202 | 1) Fork this [codesandbox](https://codesandbox.io/s/rzpxx0w34) 203 | 2) Make sure your version (under dependencies) is the latest available version 204 | 3) Update the title and description 205 | 4) Update the code for your example (add some form of documentation to explain what it is) 206 | 5) Add the tag: `statty:example` 207 | 208 | ## Inspiration 209 | 210 | * [Michael Jackson](https://github.com/mjackson)'s post on [render props](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce) 211 | * [refunk](https://github.com/jxnblk/refunk/) 212 | 213 | ## Tests 214 | 215 | ```sh 216 | $ npm run test 217 | ``` 218 | 219 | ## LICENSE 220 | 221 | [MIT License](LICENSE.md) © [Alessandro Arnodo](https://alessandro.arnodo.net/) 222 | -------------------------------------------------------------------------------- /inspect.js: -------------------------------------------------------------------------------- 1 | // to be used during development only ofc 2 | module.exports = function inspect (oldState, newState, updaterFn) { 3 | try { 4 | console.group( 5 | '%c statty%c ' + (updaterFn.name || 'Anonymous updater'), 6 | 'color: #AAAAAA', 7 | 'color: #001B44' 8 | ) 9 | } catch (e) { 10 | console.log('action') 11 | } 12 | console.log('%c old state', 'color: #E7040F', oldState) 13 | console.log('%c new state', 'color: #19A974', newState) 14 | try { 15 | console.groupEnd() 16 | } catch (e) { 17 | console.log('== end ==') 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "statty", 3 | "version": "2.0.4", 4 | "description": "A tiny and unobtrusive state management library for React and Preact apps", 5 | "module": "dist/statty.es.js", 6 | "main": "dist/statty.cjs.js", 7 | "umd:main": "dist/statty.umd.js", 8 | "scripts": { 9 | "precommit": "lint-staged", 10 | "bump": "standard-version", 11 | "testonly": "jest --coverage", 12 | "lint": "standard", 13 | "format": "prettier --write --semi false '*src/*.js' && standard --fix", 14 | "test": "npm-run-all lint testonly", 15 | "build": "npm-run-all clean rollup rollup:min", 16 | "clean": "rimraf dist", 17 | "rollup": "rollup -c", 18 | "rollup:min": "cross-env MINIFY=minify rollup -c", 19 | "release": "npm-run-all test build bump && git push --follow-tags origin master && npm publish" 20 | }, 21 | "repository": "vesparny/statty", 22 | "keywords": [ 23 | "redux", 24 | "react", 25 | "state", 26 | "setState", 27 | "mobx" 28 | ], 29 | "homepage": "https://github.com/vesparny/statty", 30 | "authors": [ 31 | "Alessandro Arnodo " 32 | ], 33 | "license": "MIT", 34 | "files": [ 35 | "dist", 36 | "src", 37 | "inspect.js" 38 | ], 39 | "devDependencies": { 40 | "babel-core": "^6.26.0", 41 | "babel-eslint": "^8.0.1", 42 | "babel-plugin-external-helpers": "^6.22.0", 43 | "babel-preset-env": "^1.6.0", 44 | "babel-preset-react": "^6.24.1", 45 | "cross-env": "^5.0.5", 46 | "enzyme": "^3.1.0", 47 | "enzyme-adapter-react-16": "^1.0.1", 48 | "enzyme-to-json": "^3.1.1", 49 | "husky": "^0.14.3", 50 | "jest": "^21.2.1", 51 | "lint-staged": "^4.2.3", 52 | "npm-run-all": "^4.1.1", 53 | "prettier": "^1.7.4", 54 | "react": "^16.0.0", 55 | "react-dom": "^16.0.0", 56 | "react-test-renderer": "^16.0.0", 57 | "rimraf": "^2.6.2", 58 | "rollup": "^0.50.0", 59 | "rollup-plugin-buble": "^0.16.0", 60 | "rollup-plugin-commonjs": "^8.2.1", 61 | "rollup-plugin-filesize": "^1.5.0", 62 | "rollup-plugin-node-resolve": "^3.0.0", 63 | "rollup-plugin-uglify": "^2.0.1", 64 | "standard": "^10.0.3", 65 | "standard-version": "^4.0.0" 66 | }, 67 | "dependencies": { 68 | "brcast": "^3.0.1", 69 | "is-shallow-equal": "^1.0.1", 70 | "prop-types": "^15.6.0" 71 | }, 72 | "peerDependencies": { 73 | "react": ">=0.15" 74 | }, 75 | "standard": { 76 | "parser": "babel-eslint", 77 | "globals": [ 78 | "jest", 79 | "expect", 80 | "it", 81 | "test", 82 | "describe" 83 | ] 84 | }, 85 | "lint-staged": { 86 | "*.js": [ 87 | "prettier --write", 88 | "standard --fix", 89 | "git add" 90 | ] 91 | }, 92 | "bundlesize": [ 93 | { 94 | "path": "./dist/*min.js" 95 | } 96 | ] 97 | } 98 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import buble from 'rollup-plugin-buble' 2 | import fileSize from 'rollup-plugin-filesize' 3 | import uglify from 'rollup-plugin-uglify' 4 | import resolve from 'rollup-plugin-node-resolve' 5 | import commonjs from 'rollup-plugin-commonjs' 6 | 7 | function makeDest (format) { 8 | return `dist/${pkg.name}.${format}${minify ? `.min` : ``}.js` 9 | } 10 | 11 | const minify = !!process.env.MINIFY 12 | const pkg = require('./package.json') 13 | 14 | let targets = [ 15 | { file: makeDest('cjs'), format: 'cjs' }, 16 | { file: makeDest('umd'), format: 'umd', name: pkg.name } 17 | ] 18 | 19 | export default { 20 | input: 'src/index.js', 21 | useStrict: false, 22 | sourcemap: minify, 23 | external: ['react', 'prop-types'], 24 | globals: { 25 | react: 'React', 26 | 'prop-types': 'PropTypes' 27 | }, 28 | plugins: [ 29 | resolve({ 30 | jsnext: true 31 | // main: false, 32 | // browser: false 33 | }), 34 | commonjs(), 35 | buble(), 36 | minify ? uglify() : {}, 37 | minify ? fileSize() : {} 38 | ], 39 | output: minify 40 | ? targets 41 | : targets.concat([{ file: makeDest('es'), format: 'es' }]) 42 | } 43 | -------------------------------------------------------------------------------- /src/__tests__/__snapshots__/provider.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Provider passes context down 1`] = ` 4 | 5 | {"state":"ok"} 6 | 7 | `; 8 | -------------------------------------------------------------------------------- /src/__tests__/__snapshots__/state.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`with count = 0 1`] = ` 4 | 11 | 15 | 20 | 21 | 22 | `; 23 | 24 | exports[`with count = 1 1`] = ` 25 | 32 | 36 | 41 | 42 | 43 | `; 44 | 45 | exports[`with count = 10 1`] = ` 46 | 53 | 62 | 67 | 68 | 69 | `; 70 | 71 | exports[`with count = 11 1`] = ` 72 | 79 | 88 | 93 | 94 | 95 | `; 96 | 97 | exports[`with no render prop 1`] = ` 98 | 105 | 109 | 110 | `; 111 | 112 | exports[`with selector 1`] = ` 113 | 121 | 125 | 126 | {"data":[]} 127 | 128 | 129 | 130 | `; 131 | -------------------------------------------------------------------------------- /src/__tests__/index.test.js: -------------------------------------------------------------------------------- 1 | import * as statty from '../index' 2 | 3 | test('exposes the public API', () => { 4 | const methods = Object.keys(statty) 5 | expect(methods.length).toBe(2) 6 | expect(methods).toContain('Provider') 7 | expect(methods).toContain('State') 8 | }) 9 | -------------------------------------------------------------------------------- /src/__tests__/provider.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import Enzyme, { render } from 'enzyme' 3 | import serializer from 'enzyme-to-json/serializer' 4 | import { Provider, State } from '../index' 5 | import Adapter from 'enzyme-adapter-react-16' 6 | 7 | Enzyme.configure({ adapter: new Adapter() }) 8 | expect.addSnapshotSerializer(serializer) 9 | 10 | test('Provider passes context down', () => { 11 | expect( 12 | render( 13 | 14 | {JSON.stringify(state)}} 16 | /> 17 | 18 | ) 19 | ).toMatchSnapshot() 20 | }) 21 | -------------------------------------------------------------------------------- /src/__tests__/state.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import Enzyme, { mount } from 'enzyme' 3 | import serializer from 'enzyme-to-json/serializer' 4 | import { Provider, State } from '../index' 5 | import Adapter from 'enzyme-adapter-react-16' 6 | 7 | Enzyme.configure({ adapter: new Adapter() }) 8 | 9 | const CHANNEL = '__statty__' 10 | 11 | expect.addSnapshotSerializer(serializer) 12 | 13 | const increment = state => ({ count: state.count + 1 }) 14 | const getMockedContext = () => ({ 15 | [CHANNEL]: { 16 | broadcast: { 17 | getState: () => {}, 18 | setState: () => {}, 19 | subscribe: () => 1, 20 | unsubscribe: jest.fn() 21 | } 22 | } 23 | }) 24 | 25 | test('Connector updates global state', () => { 26 | const state = { count: 0 } 27 | const wrapper = mount( 28 | 29 | ( 31 | 32 | )} 33 | /> 34 | 35 | ) 36 | expect(wrapper).toMatchSnapshot(`with count = 0`) 37 | wrapper.find('button').simulate('click') 38 | expect(wrapper).toMatchSnapshot(`with count = 1`) 39 | }) 40 | 41 | test('Connector updates local state', () => { 42 | const wrapper = mount( 43 | 44 | ( 47 | 48 | )} 49 | /> 50 | 51 | ) 52 | expect(wrapper).toMatchSnapshot(`with count = 10`) 53 | wrapper.find('button').simulate('click') 54 | expect(wrapper).toMatchSnapshot(`with count = 11`) 55 | }) 56 | 57 | test('Connector returns a slice of the state based on a selector function', () => { 58 | const selector = state => ({ data: state.data }) 59 | const wrapper = mount( 60 | 61 | {JSON.stringify(state)}} 64 | /> 65 | 66 | ) 67 | expect(wrapper).toMatchSnapshot(`with selector`) 68 | }) 69 | 70 | test('Connector returns null in case no render prop is provided', () => { 71 | const wrapper = mount( 72 | 73 | 74 | 75 | ) 76 | expect(wrapper).toMatchSnapshot(`with no render prop`) 77 | }) 78 | 79 | test('unsubscribes from state updates on unmount', () => { 80 | const context = getMockedContext() 81 | const wrapper = mount( } />, { 82 | context 83 | }) 84 | wrapper.unmount() 85 | expect(context[CHANNEL].broadcast.unsubscribe).toHaveBeenCalled() 86 | }) 87 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import State from './state' 2 | import Provider from './provider' 3 | 4 | export { Provider, State } 5 | -------------------------------------------------------------------------------- /src/provider.js: -------------------------------------------------------------------------------- 1 | import { Component } from 'react' 2 | import PropTypes from 'prop-types' 3 | import brcast from 'brcast' 4 | 5 | class Provider extends Component { 6 | constructor (props, context) { 7 | super(props, context) 8 | this.broadcast = brcast(props.state) 9 | } 10 | 11 | getChildContext () { 12 | return { 13 | __statty__: { 14 | broadcast: this.broadcast, 15 | inspect: this.props.inspect 16 | } 17 | } 18 | } 19 | 20 | render () { 21 | const children = this.props.children 22 | return Array.isArray(children) ? children[0] : children 23 | } 24 | } 25 | 26 | Provider.childContextTypes = { 27 | __statty__: PropTypes.object 28 | } 29 | 30 | Provider.propTypes = { 31 | inspect: PropTypes.func, 32 | state: PropTypes.object.isRequired, 33 | children: PropTypes.node.isRequired 34 | } 35 | 36 | export default Provider 37 | -------------------------------------------------------------------------------- /src/state.js: -------------------------------------------------------------------------------- 1 | import { Component } from 'react' 2 | import PropTypes from 'prop-types' 3 | import shallowEqual from 'is-shallow-equal' 4 | 5 | const isObjectNotNull = (a, b) => { 6 | return ( 7 | typeof a === 'object' && typeof b === 'object' && a !== null && b !== null 8 | ) 9 | } 10 | 11 | class State extends Component { 12 | constructor (props, context) { 13 | super(props, context) 14 | this.broadcast = context.__statty__.broadcast 15 | this.inspect = context.__statty__.inspect 16 | this.state = props.state 17 | ? props.state 18 | : props.select(this.broadcast.getState()) 19 | this.update = this.update.bind(this) 20 | this.setStateIfNeeded = this.setStateIfNeeded.bind(this) 21 | } 22 | 23 | update (updaterFn) { 24 | if (this.props.state) { 25 | this.setState(updaterFn) 26 | } else { 27 | const oldState = this.broadcast.getState() 28 | const nextState = updaterFn(oldState) 29 | this.inspect && this.inspect(oldState, nextState, updaterFn) 30 | this.broadcast.setState(nextState) 31 | } 32 | } 33 | 34 | setStateIfNeeded (nextState) { 35 | const oldSelectdedState = this.state 36 | const newSelectedState = this.props.select(nextState) 37 | if ( 38 | !isObjectNotNull(oldSelectdedState, newSelectedState) || 39 | !shallowEqual(oldSelectdedState, newSelectedState) 40 | ) { 41 | this.setState(newSelectedState) 42 | } 43 | } 44 | 45 | componentDidMount () { 46 | if (!this.props.state) { 47 | this.subscriptionId = this.broadcast.subscribe(this.setStateIfNeeded) 48 | // To handle the case where a child component may have triggered a state change in 49 | // its cWM/cDM, we have to re-run the selector and maybe re-render. 50 | this.setStateIfNeeded(this.broadcast.getState()) 51 | } 52 | } 53 | 54 | componentWillUnmount () { 55 | this.subscriptionId && this.broadcast.unsubscribe(this.subscriptionId) 56 | } 57 | 58 | render () { 59 | return ( 60 | this.props.render( 61 | this.props.select( 62 | this.props.state ? this.state : this.broadcast.getState() 63 | ), 64 | this.update 65 | ) || null 66 | ) 67 | } 68 | } 69 | 70 | State.defaultProps = { 71 | select: s => s, 72 | render: () => null 73 | } 74 | 75 | State.contextTypes = { 76 | __statty__: PropTypes.object.isRequired 77 | } 78 | 79 | State.propTypes = { 80 | state: PropTypes.object, 81 | render: PropTypes.func, 82 | select: PropTypes.func 83 | } 84 | 85 | export default State 86 | --------------------------------------------------------------------------------