syncbasestore
Version:
Lightweight reactive store with built-in filtering and async state handling
61 lines (60 loc) • 2.14 kB
JavaScript
import get from 'lodash.get';
import set from 'lodash.set';
export function tileBase(store, key) {
return {
get() {
return store.getState()[key];
},
getField(path) {
return get(store.getState()[key], path);
},
set(value) {
store.build(prev => ({ ...prev, [key]: value }));
},
update(updater) {
store.build(prev => ({ ...prev, [key]: updater(prev[key]) }));
},
setField(path, value) {
const current = { ...store.getState()[key] };
set(current, path, value);
store.build(prev => ({ ...prev, [key]: current }));
},
claim(selector) {
return () => selector(store.getState()[key]);
},
target(path) {
return (value) => {
const current = { ...store.getState()[key] };
set(current, path, value);
store.build(prev => ({ ...prev, [key]: current }));
};
},
clear() {
const initial = store.getInitialState()[key];
store.build(prev => ({ ...prev, [key]: structuredClone(initial) }));
},
clearOnly(...fields) {
const initial = store.getInitialState()[key];
const current = store.getState()[key];
const updated = { ...current };
for (const field of fields) {
updated[field] = structuredClone(initial[field]);
}
store.build(prev => ({ ...prev, [key]: updated }));
},
clearKeep(fields) {
const initial = store.getInitialState()[key];
const current = store.getState()[key];
const updated = {};
for (const field of fields) {
updated[field] = structuredClone(current[field]);
}
for (const field in initial) {
if (!fields.includes(field)) {
updated[field] = structuredClone(initial[field]);
}
}
store.build(prev => ({ ...prev, [key]: updated }));
}
};
}