Last active
January 7, 2018 19:50
-
-
Save wtfaremyinitials/7bb0a77e47f435541287dd8185891f00 to your computer and use it in GitHub Desktop.
Meteor-style client-side database + Redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Meteor-style client-side database + Redux | |
// kind of a hack. not idiomatic Redux | |
// might become an npm module at some point idk | |
import PouchDB from 'pouchdb' | |
export function databaseReducer(state = {}, action) { | |
if (action.type === 'DATABASE_UPDATE') { | |
return Object.assign({}, state, { [action.db]: action.docs }) | |
} | |
return state | |
} | |
export function databaseSetup(store, name) { | |
const database = new PouchDB(name) | |
if (!window.DB) window.DB = {} | |
window.DB[name] = database | |
function update() { | |
// super inefficient to dump all docs each time. should really replace | |
// the docs listed in the change event | |
database.allDocs({ include_docs: true }).then(res => { | |
const docs = res.rows.map(obj => obj.doc) | |
store.dispatch({ type: 'DATABASE_UPDATE', db: name, docs }) | |
}) | |
} | |
database.changes({ since: 'now', live: true }).on('change', update) | |
update() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment