Skip to content

Instantly share code, notes, and snippets.

@wtfaremyinitials
Last active January 7, 2018 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wtfaremyinitials/7bb0a77e47f435541287dd8185891f00 to your computer and use it in GitHub Desktop.
Save wtfaremyinitials/7bb0a77e47f435541287dd8185891f00 to your computer and use it in GitHub Desktop.
Meteor-style client-side database + Redux
// 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