Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement for "store" make it more robust #10

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 53 additions & 24 deletions src/store/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// @flow
/* eslint no-underscore-dangle: 0 */ // --> OFF

import { AsyncStorage } from 'react-native';
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
// eslint-disable-next-line
Expand All @@ -7,27 +10,40 @@ import api from './api';
import firebase from './firebase';
import reducers from '../reducers';

const middlewares = [
api,
firebase,
];

if (__DEV__ === true) {
middlewares.push(createLogger({
duration: true,
timestamp: true,
diff: true,
}));
}
// wrapper for redux store
export class AppStore {
constructor() {
this.store = null;
}

const appStore = {
setStore(store) {
appStore.store = store;
},
getStore() {
return appStore.store;
},
createStore(onComplete: ?() => void) {
get store(): Object {
if (!this.__store__) {
throw Error('store not yet created, must call createStore() before accessing store');
}
return this.__store__;
}

set store(store: Object): void {
this.__store__ = store;
}

get loaded(): boolean {
return !!this.__store__;
}

createStore(onComplete: ?() => void): Object {
const middlewares = [
api,
firebase,
];

if (__DEV__) {
middlewares.push(createLogger({
duration: true,
timestamp: true,
diff: true,
}));
}
const store = createStore(
combineReducers(reducers),
compose(
Expand All @@ -37,9 +53,22 @@ const appStore = {
);

persistStore(store, { storage: AsyncStorage }, onComplete);
appStore.setStore(store);
this.store = store;
return store;
},
};
}
}

export default appStore;
// a proxy for appStore api to provide some magic.
// caller can access redux store's properties directly.
// for example: appStore.getState()
export default new Proxy(new AppStore(), {
get(target, key) {
const disallowedProps = ['store', '__store__'];
if (disallowedProps.includes(key)) {
return undefined;
} else if (target[key]) {
return target[key];
}
return target.store[key];
},
});