Commit a7d193f4 authored by Nathan Faucett's avatar Nathan Faucett
Browse files

clean up

parents
{
"parserOptions": {
"ecmaVersion": 3,
"sourceType": "module"
},
"rules": {
"no-unused-vars": "error",
"eqeqeq": "error",
"curly": "error",
"quotes": ["warn", "double"]
}
}
\ No newline at end of file
node_modules
npm-debug.log
yarn-error.log
node_modules
tests
npm-debug.log
.npmignore
.gitignore
.eslintrc.json
The MIT License (MIT)
Copyright (c) 2018 Nathan Faucett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# js-state-react
connect react components with state stores
## State Stores
```javascript
import State from "@nathanfaucett/state";
const state = new State();
let ID = 0;
const todos = state.createStore("todos", {
list: []
});
todos.create = text => {
const id = ID++;
todos.updateState(state => {
const list = state.list.slice();
list.push({
id: id,
text: text
});
return {
list: list
};
});
};
todos.remove = id => {
todos.updateState(state => {
const index = list.findIndex(todo => todo.id === id);
let list = state.list;
if (index !== -1) {
list = list.slice();
list.slice(index, 1);
}
return {
list: list
};
});
};
```
## Components
```javascript
import React from "react";
import connect from "@nathanfaucett/state-react";
import state from "./state";
import todos from "./stores/todos";
// create store for form input
let todoListForm = state.createStore("todoListForm", { text: "" });
class TodoList extends React.Component {
constructor(props) {
super(props);
this.onSubmit = e => {
e.preventDefault();
todos.create(this.props.todoListForm.text);
todoListForm.setState({ text: "" });
};
this.onChange = e => {
todoListForm.setState({ text: e.target.value });
};
}
render() {
return (
<div class="TodoList">
<form onSubmit={this.onSubmit}>
<input
value={this.props.todoListForm.text}
onChange={this.onChange}
/>
</form>
{this.props.todos.list.map(todo => (
<p key={todo.id}>{todo.text}</p>
))}
</div>
);
}
}
// update TodoList when todos or todoListForm emit an update
// on update adds todos state and todoListForm state to props
export default connect(
TodoList,
[todos, todoListForm],
// optional
(nextState, nextProps) => {
// called on render should extract values from nextState to pass to component props
return nextState;
},
// optional
(prevState, nextState, props) => {
// called on update, if returns false cancels update
}
);
```
This diff is collapsed.
{
"name": "@nathanfaucett/state-react",
"version": "0.2.0",
"description": "connect react components with state stores",
"repository": {
"type": "git",
"url": "https://gitlab.com/nathanfaucett/js-state-react.git"
},
"main": "src/index.js",
"scripts": {
"test": "zuul --local 9999 --ui tape -- ./tests"
},
"keywords": [
"state",
"react",
"connect"
],
"author": "Nathan Faucett",
"license": "MIT",
"readmeFilename": "README.md",
"devDependencies": {
"@nathanfaucett/state": ">= 0.3",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"react": ">= 15.x",
"react-dom": "^16.2.0",
"tape": "^4.9.0",
"zuul": "^3.11.1"
},
"dependencies": {
"@nathanfaucett/array-for_each": "^0.0.1",
"@nathanfaucett/deep_equals": "0.0.1",
"@nathanfaucett/extend": "^0.0.2",
"@nathanfaucett/inherits": "^0.0.3",
"@nathanfaucett/is_array": "^0.0.1",
"@nathanfaucett/is_function": "^0.0.1"
},
"peerDependencies": {
"react": ">= 15.x"
}
}
var React = require("react"),
isArray = require("@nathanfaucett/is_array"),
isFunction = require("@nathanfaucett/is_function"),
arrayForEach = require("@nathanfaucett/array-for_each"),
inherits = require("@nathanfaucett/inherits"),
extend = require("@nathanfaucett/extend"),
deepEquals = require("@nathanfaucett/deep_equals");
module.exports = connect;
function connect(Component, stores, mapping, shouldUpdate) {
var Connect, ConnectPrototype;
if (!isArray(stores)) {
throw new TypeError(
"connect(Component, stores[, mapping[, shouldUpdate]]) stores must be an Array"
);
}
if (!isFunction(mapping)) {
mapping = defaultMapping;
}
if (!isFunction(shouldUpdate)) {
shouldUpdate = defaultShouldUpdate;
}
function Connect(props) {
var _this = this;
React.Component.call(this, props);
this._state = this._nextState();
this._updating = false;
this._isMounted = false;
this._onUpdate = function onUpdate() {
if (!_this._updating) {
_this._updating = true;
process.nextTick(function onNextTick() {
_this._updating = false;
_this._updateIfNeeded(_this._nextState());
});
}
};
arrayForEach(stores, function each(store) {
store.on("update", _this._onUpdate);
});
}
inherits(Connect, React.Component);
ConnectPrototype = Connect.prototype;
Connect.displayName =
"Connect(" +
(Component.displayName || Component.name || "Component") +
")";
ConnectPrototype._nextState = function() {
var localStores = stores,
state = {};
arrayForEach(localStores, function each(store) {
state[store.name()] = store.state();
});
return state;
};
ConnectPrototype._updateIfNeeded = function(nextState) {
if (this._isMounted) {
if (
shouldUpdate.call(
this.refs.component,
this._state,
nextState,
this.props
) !== false
) {
this._state = nextState;
this.forceUpdate();
}
}
};
ConnectPrototype.componentDidMount = function() {
this._isMounted = true;
};
ConnectPrototype.componentWillUnmount = function() {
var _this = this;
arrayForEach(stores, function each(store) {
store.off("update", _this._onUpdate);
});
this._isMounted = false;
};
ConnectPrototype.render = function() {
return React.createElement(
Component,
extend(
{ ref: "component" },
this.props,
mapping(this._state, this.props)
)
);
};
return Connect;
}
function defaultShouldUpdate(prevState, nextState) {
return !deepEquals(prevState, nextState);
}
function defaultMapping(nextState /*, props*/) {
return nextState;
}
connect.defaultShouldUpdate = defaultShouldUpdate;
connect.defaultMapping = defaultMapping;
module.exports = require("./connect");
var tape = require("tape"),
React = require("react"),
Enzyme = require("enzyme"),
EnzymeAdapter = require("enzyme-adapter-react-16"),
State = require("@nathanfaucett/state"),
inherits = require("@nathanfaucett/inherits"),
deepEquals = require("@nathanfaucett/deep_equals"),
connect = require("..");
var state = new State(),
formStore = state.createStore("form", { text: "" }),
RENDER_CALLED = 0,
MAPPING_CALLED = 0,
PREDICATE_CALLED = 0;
Enzyme.configure({ adapter: new EnzymeAdapter() });
function Form(props) {
React.Component.call(this, props);
}
inherits(Form, React.Component);
Form.prototype.render = function() {
RENDER_CALLED += 1;
return React.createElement(
"form",
null,
React.createElement("input", {
onChange: function(e) {
formStore.setState({
text: e.target.value
});
},
type: "text",
ref: "input",
value: this.props.form.text
})
);
};
var ConnectedForm = connect(
Form,
[formStore],
function mapping(nextState /*, nextProps */) {
MAPPING_CALLED += 1;
return nextState;
},
function shouldUpdate(prevState, nextState /*, props */) {
console.log(prevState, nextState);
PREDICATE_CALLED += 1;
return !deepEquals(prevState, nextState);
}
);
tape("connect update", function(assert) {
var wrapper = Enzyme.mount(React.createElement(ConnectedForm));
assert.equals(
wrapper.instance().constructor.displayName,
"Connect(Form)",
"should wrap component name"
);
assert.equals(formStore.state()["text"], "", "store text should be empty");
assert.equals(
wrapper.instance().refs.component.props.form.text,
"",
"component props should reflect stores"
);
wrapper.find("input").simulate("change", { target: { value: "text" } });
setTimeout(function() {
assert.equals(
formStore.state()["text"],
"text",
"store's value should update"
);
assert.equals(
wrapper.instance().refs.component.props.form.text,
"text",
"text should update to new store's value"
);
wrapper.find("input").simulate("change", { target: { value: "text" } });
setTimeout(function() {
assert.equals(
formStore.state()["text"],
"text",
"store's text should not have changed"
);
assert.equals(
wrapper.instance().refs.component.props.form.text,
"text",
"text should not have changed"
);
wrapper.unmount();
assert.equals(
PREDICATE_CALLED,
2,
"predicate should have been called"
);
assert.equals(MAPPING_CALLED, 2, "mapping should have been called");
assert.equals(RENDER_CALLED, 2, "render should have been called");
assert.end();
});
});
});
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment