Treating firebase as the single source of true: Replacing redux state always when a new event come

This commit is contained in:
Bruno Lemos
2017-03-11 17:17:31 -03:00
parent 6d0657b149
commit 3cc5febd82
3 changed files with 13 additions and 19 deletions

View File

@@ -34,6 +34,7 @@ const indexReducer = (state: Object = initialState, action) => {
if (!(statePathArr && statePathArr.length)) return state;
switch (eventName) {
case 'child_added': return state.mergeDeepIn(statePathArr, fromJS(value));
case 'child_removed': return state.removeIn(statePathArr);
default: return state.setIn(statePathArr, fromJS(value));
}

View File

@@ -64,22 +64,14 @@ export function startFirebase({ store, userId }) {
_databaseRef = firebase.database().ref(`users/${userId}/`);
console.debug('[FIREBASE] Connected.');
_databaseRef.once('value', snapshot => {
_lastState = fromJS(snapshot.val()) || null;
watchFirebaseFromMap({
callback({ eventName, firebasePathArr, statePathArr, value }) {
if (_lastState === undefined) return;
store.dispatch(firebaseReceivedEvent({ eventName, firebasePathArr, statePathArr, value }));
_lastState = store.getState();
},
debug: __DEV__,
map: mapFirebaseToState,
ref: _databaseRef,
});
}, (...args) => {
console.error('[FIREBASE] Something went wrong getting data from the server', ...args);
_lastState = null;
watchFirebaseFromMap({
callback({ eventName, firebasePathArr, statePathArr, value }) {
store.dispatch(firebaseReceivedEvent({ eventName, firebasePathArr, statePathArr, value }));
_lastState = store.getState();
},
debug: __DEV__,
map: mapFirebaseToState,
ref: _databaseRef,
});
}

View File

@@ -113,7 +113,7 @@ export function createFirebaseHandler(
}
export const addFirebaseListener = (
{ blacklist, callback, debug, eventName, ref },
{ blacklist, callback, debug, eventName, ref, ...rest },
) => {
const fullPath = getPathFromRef(ref);
let message = `[FIREBASE] Watching ${fullPath} ${eventName}`;
@@ -122,7 +122,7 @@ export const addFirebaseListener = (
message = `${message}, except ${blacklist.join(', ')}`;
}
if (debug) console.debug(message);
if (debug && !rest.isRecursiveCall) console.debug(message);
if (eventName === 'children' || Array.isArray(eventName)) {
const eventNames = Array.isArray(eventName)
@@ -133,9 +133,10 @@ export const addFirebaseListener = (
addFirebaseListener({
blacklist,
callback,
debug: false,
debug,
eventName: realEventName,
ref,
isRecursiveCall: true,
});
});