Skip to content

Commit

Permalink
feat(createContextHandler): updates to createContextHandler for consi…
Browse files Browse the repository at this point in the history
…stent application of documented

affects: @tao.js/react

createContextHandler now does the following:
* provides the current state as the last arg to the configured handler
* the set function passed to the configured handler will be used to
  overwrite the state
* the set function passed will prevent returned data from being shallow merged
  • Loading branch information
eudaimos committed Jan 25, 2019
1 parent 975753c commit b882630
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions packages/react-tao/src/createContextHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ import { AppCtx } from '@tao.js/core';
import { normalizeAC, cleanInput } from './helpers';
import { Context } from './Provider';

function cleanState(previousState, newState) {
return Object.keys(previousState)
.concat(Object.keys(newState))
.reduce((rv, key) => {
rv[key] = newState[key];
return rv;
}, {});
}

export default function createContextHandler(tao, handler, defaultValue) {
if (handler != null && typeof handler !== 'function') {
throw new Error('createContextHandler `handler` must be a function');
Expand Down Expand Up @@ -40,15 +49,25 @@ export default function createContextHandler(tao, handler, defaultValue) {
}

contextHandler = (tao, data) => {
let usedSet = false;
const current = this.state;
const dataUpdate = handler
? handler(tao, data, data => this.setState(data))
? handler(
tao,
data,
data => {
const update = cleanState(current, data);
this.setState(update);
usedSet = true;
},
current
)
: data;
if (dataUpdate instanceof AppCtx) {
return dataUpdate;
}
if (dataUpdate != null) {
const newState = Object.assign({}, this.state, dataUpdate);
this.setState(newState);
if (!usedSet && dataUpdate != null) {
this.setState(dataUpdate);
}
};

Expand Down

0 comments on commit b882630

Please sign in to comment.