Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active March 19, 2021 17:05
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 james2doyle/de062f26764fed284eeebd20473c1c5a to your computer and use it in GitHub Desktop.
Save james2doyle/de062f26764fed284eeebd20473c1c5a to your computer and use it in GitHub Desktop.
A reactive datastore using lodash as the backend
import { reactive } from '@vue/reactivity';
import lodash from 'lodash';
const defaultState = {
count: 1
};
/**
* Create a database that is reactive
*/
const makeDb = (state = {}) => {
const store = reactive(state);
return lodash.chain(store);
};
export default makeDb({ state: defaultState });
<template>
<button @click.prevent="updateCount">count is: {{ count }}</button>
</template>
<script setup>
import { ref, watchEffect } from 'vue';
import db from 'lodash-reactive-store.js';
const counter = db.get('state.count');
const count = ref(counter.value());
const updateCount = () => {
// must call `.value()` to trigger the effect
db.set('state.count', count.value + 1).value();
}
// runs on updates of the db state
watchEffect(() => {
// fetch the fresh value from the db state
count.value = counter.value();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment