Skip to content

Instantly share code, notes, and snippets.

@dayitv89
Last active April 10, 2019 13:13
Show Gist options
  • Save dayitv89/d1c4b19242baeff859d9cd8ab1e22aff to your computer and use it in GitHub Desktop.
Save dayitv89/d1c4b19242baeff859d9cd8ab1e22aff to your computer and use it in GitHub Desktop.
LightRedux is the lightest version of the redux, no actions, no reducers, no funny business direct HOC based implementation. Good for small project.
/**
* Copyright (c) 2017-Present, Gaurav D. Sharma
* All rights reserved.
*
* @flow
*/
'use strict';
import React from 'react';
const hasChange = function(oldObj, newObj) {
if (!oldObj) {
if (!newObj) {
return false;
}
return true;
} else if (!newObj) {
return true;
}
const oldKeys = Object.keys(oldObj);
const newKeys = Object.keys(newObj);
if (oldKeys.length !== newKeys.length) {
return true;
}
const hasDiff = newKeys.find(key => oldObj[key] !== newObj[key]);
return !!hasDiff;
};
class LightStore {
constructor() {
this.data = {};
this._listeners = {};
}
_storeValidData = d => {
if (!this.data || Object.keys(this.data).length == 0) {
this.data = d;
} else {
this.data = { ...this.data, ...d };
}
};
init = this._storeValidData;
setData = d => {
this._storeValidData(d);
Object.keys(this._listeners).forEach(id => {
this._listeners[id](this.data);
});
};
listen = (id, cb) => {
this._listeners[id] = cb;
};
stopListen = id => {
delete this._listeners[id];
};
}
const lightStore = new LightStore();
const connect = (SomeComponent, getters, shouldChange = hasChange) => {
return class extends React.Component {
constructor(props) {
super(props);
this.state = { newProps: getters(lightStore.data, props) };
this.id = `id_${Math.random()}`;
lightStore.listen(this.id, storeData => {
const newProps = getters(storeData, this.props);
if (shouldChange(this.state.newProps, newProps)) {
this.setState({ newProps });
}
});
}
componentWillUnmount() {
lightStore.stopListen(this.id);
}
render() {
return <SomeComponent {...this.props} {...this.state.newProps} />;
}
};
};
module.exports = {
lightStore,
connect
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment