undux
Version:
Dead simple state management for React
86 lines • 2.4 kB
JavaScript
import { Emitter } from './emitter';
import { mapValues } from './utils';
/**
* Immutable snapshot of the current store state. One StoreSnapshot per
* StoreDefinition is usually alive at a time.
*/
export class StoreSnapshot {
constructor(state, storeDefinition) {
this.state = state;
this.storeDefinition = storeDefinition;
}
get(key) {
return this.state[key];
}
set(key) {
return this.storeDefinition.set(key);
}
setFrom_EXPERIMENTAL(f) {
return this.storeDefinition.setFrom_EXPERIMENTAL(f);
}
on(key) {
return this.storeDefinition.on(key);
}
onAll() {
return this.storeDefinition.onAll();
}
getState() {
return Object.freeze(this.state);
}
}
let DEFAULT_OPTIONS = {
isDevMode: false,
};
/**
* We create a single instance of this per <Container />.
*/
export class StoreDefinition {
constructor(state, options) {
// Initialize emitters
this.alls = new Emitter(options.isDevMode);
this.emitter = new Emitter(options.isDevMode);
// Set initial state
this.storeSnapshot = new StoreSnapshot(state, this);
// Cache setters
this.setters = mapValues(state, (v, key) => (value) => {
let previousValue = this.storeSnapshot.get(key);
this.storeSnapshot = new StoreSnapshot(Object.assign({}, this.storeSnapshot.getState(), { [key]: value }), this);
this.emitter.emit(key, value);
this.alls.emit(key, { key, previousValue, value });
});
}
on(key) {
return this.emitter.on(key);
}
onAll() {
return this.alls.all();
}
get(key) {
return this.storeSnapshot.get(key);
}
set(key) {
return this.setters[key];
}
setFrom_EXPERIMENTAL(f) {
return f(this.storeSnapshot);
}
getCurrentSnapshot() {
return this.storeSnapshot;
}
toStore() {
return this.storeSnapshot;
}
getState() {
return this.storeSnapshot.getState();
}
}
/**
* @deprecated Use `createConnectedStore` instead.
*/
export function createStore(initialState, options = DEFAULT_OPTIONS) {
return new StoreDefinition(initialState, options);
}
export * from './plugins/withLogger';
export * from './plugins/withReduxDevtools';
export * from './react';
//# sourceMappingURL=index.js.map