3 ms·
You can also inject sideways data dependencies in React by using an event emitter. Shitty POC: // global-store.js const remove = (arr, el) => { const i
by anonytrary 8y ago
You can also inject sideways data dependencies in React by using an event emitter. Shitty POC:
// global-store.js
const remove = (arr, el) => {
const i = arr.indexOf(el);
if (i < 0) return false;
return !!arr.splice(i, 1);
}
class GlobalStore {
constructor(data){
this.data = data;
this.subs = [];
}
sub(cb){this.subs.push(cb)}
unsub(cb){remove(this.subs, cb)}
notify(newArr){
for (let s of this.subs)
s(newArr);
}
addData(item){
notify(this.data = [...data, item])
}
removeData(item){
if (remove(this.data, item))
notify(this.data = [...this.data])
}
}
// my-component.js
import myStore from "./stores"
class MyComp extends Component {
...
componentDidMount(){
myStore.sub(this._cb = data => {
this.setState({data})
})
}
componentWillUnmount(){
myStore.unsub(this._cb)
}
}
Obviously, not super optimized, but it's just a POC.