Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
redux middleware with firebase replay / remote actions
import Firebase from 'firebase';
const firebaseUrl = 'https://spatially.firebaseio.com/clients';
const timeOffsetUrl = 'https://spatially.firebaseio.com/.info/serverTimeOffset';
let ref = new Firebase(firebaseUrl);
let timeRef = new Firebase(timeOffsetUrl);
let cachedUid;
export default ({dispatch, getState}) => next => action => {
// The first action rehydrates, so now we've probably got the uid now
let result = next(action);
let { uid } = getState().info || {};
if (!uid)
return;
if (uid !== cachedUid) {
// Potentially first time!
if (cachedUid)
ref.child(cachedUid).child('actions').off();
// We make sure the event isn't old by correlating events with server time
timeRef.once('value', snap => {
let offset = snap.val();
let acceptedEventTime = Date.now() + offset;
console.log(offset)
ref.child(uid).child('actions').limitToLast(1).on('child_added', snap => {
let action = snap.val();
if (action.time && action.time + offset > acceptedEventTime) {
console.log('Running remote action', action);
dispatch(action);
} else {
console.log('got an .. old? event', action);
}
});
});
cachedUid = uid;
}
ref.child(uid).child('state').push(result);
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment