Skip to content

Instantly share code, notes, and snippets.

@wegorich
Created January 23, 2018 22:27
Show Gist options
  • Save wegorich/536e6bcb8edb08669687ac2a99b1d84f to your computer and use it in GitHub Desktop.
Save wegorich/536e6bcb8edb08669687ac2a99b1d84f to your computer and use it in GitHub Desktop.
use-store-decorator.ts make it TS friendly
import { bindActionCreators } from 'redux';
// @ts-ignore
import { simpleActions } from 'redux-pirate-actions';
export abstract class UseStore {
actions: any;
store: any;
private errorTimeout: any;
private _unsubscribe: any;
syncInit() {
this.syncUnsubscribe();
this._sync();
this._unsubscribe = this.store.subscribe(this._sync.bind(this));
}
syncUnsubscribe() {
this._unsubscribe && this._unsubscribe();
this._unsubscribe = null;
}
_sync() {
// @ts-ignore
if (this.sync) {
let state = this.store.getState();
// @ts-ignore
this.sync(state);
}
}
showErrors(state: any): any {
if (state.errors.length > 0) {
let err = state.errors[state.errors.length - 1];
let message = err.message ||
err.data && err.data.error || err;
if (message) {
// avoid showing same error multiple times
clearTimeout(this.errorTimeout);
this.errorTimeout = setTimeout(()=> {
// @ts-ignore
if (!this.toast) {
console.warn(typeof this, ' should have *this.toast* object to show errors: ', message);
} else {
// @ts-ignore
this.toast.error(message);
}
}, 50);
}
this.actions.clearErrors();
}
}
// the sync sould be overrided;
//
// function sync(state: any): any {
// console.log('default sync')
// }
// it also can be overrided
// please use super.bind in this situation
//
bind() {
this.syncInit();
}
// this kind of optimization
// cause bind / unbind never trigger more then once for views
attached() {
this.syncInit();
}
// this kind of optimization
detached() {
this.syncUnsubscribe();
}
unbind() {
this.syncUnsubscribe();
}
}
export const useStoreDecorator = (actions: any, store: any) => {
let actionsCallbacks: any = null;
let actionsWr: any = null;
actionsWr = actionsWr || simpleActions(actions);
actionsCallbacks = (actionsCallbacks || bindActionCreators(actionsWr, store.dispatch)) as Object;
UseStore.prototype.actions = actionsCallbacks;
UseStore.prototype.store = store;
return UseStore;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment