Giter Club home page Giter Club logo

vuexfire's Introduction

This package has been moved to vuejs/vuefire repository.


VuexFire Build Status npm package coverage size

SSR ready Firebase binding for Vuex

Supports only Vue 2, Vuex 2 and Firebase JavaScript SDK 2/3/4/5. If you need an older version check the v1 branch: npm i -D vuexfire@v1

Installation

  1. Using a CDN:
<script src="https://unpkg.com/vuexfire@next"></script>
  1. In module environments, e.g CommonJS:
npm install vue firebase vuexfire@next --save

Usage

Add the mutations to your root Store and make sure to define the property you want to bind in the state first:

import { firebaseMutations } from 'vuexfire'
const store = new Vuex.Store({
  state: {
    todos: [], // Will be bound as an array
    user: null // Will be bound as an object
  },
  mutations: {
    // your mutations
    ...firebaseMutations
  }
})

It works with modules as well, but you don't need to add the mutations there:

const store = new Vuex.Store({
  modules: {
    todos: {
      state: {
        todos: [], // Will be bound as an array
        user: null // Will be bound as an object
      },
    }
  }
})

In order to use VuexFire, you have to enhance actions. This action enhancer takes the actual action and enhances it with two additional parameters in the context, bindFirebaseRef and unbindFirebaseRef:

import { firebaseAction } from 'vuexfire'

const setTodosRef = firebaseAction(({ bindFirebaseRef, unbindFirebaseRef }, { ref }) => {
  // this will unbind any previously bound ref to 'todos'
  bindFirebaseRef('todos', ref)
  // you can unbind any ref easily
  unbindFirebaseRef('user')
})

Access it as a usual piece of the state:

const Component = {
  template: '<div>{{ todos }}</div>',
  computed: Vuex.mapState(['todos']),
  created () {
    this.$store.dispatch('setTodosRef', db.collection('todos'))
  }
}

Browser support

VuexFire requires basic WeakMap support, which means that if you need to support any of these browsers:

  • IE < 11
  • Safari < 7.1
  • Android < 5.0

You'll have to include a polyfill. You can use Benvie/WeakMap.

You can find more information about WeakMap support here.

How does it work?

VuexFire uses multiple global mutations prefixed by vuexfire/ to call the actual mutations to modify objects and arrays. It listens for updates to your firebase database and commits mutations to sync your state. Thanks to the action enhancer firebaseAction, it gets access to the local state and commit so it works with modules too πŸ‘

Examples

You can check out a complete example in the /examples directory.

API

firebaseMutations

This object contains VuexFire internal mutations. They are all prefixed by vuexfire/. This object must be added in the root Store mutations object.

bindFirebaseRef(key, ref)

Only available inside of an enhanced action

Binds a firebase reference to a property in the state. If there was already another reference bound to the same property, it unbinds it first.

bindFirebaseRef('todos', ref)

Returns a promise which will resolve when the data is ready, or throw an error if something goes wrong:

bindFirebaseRef('todos', ref).then(() => {
  commit('setTodosLoaded', true)
}).catch((err) => {
  console.log(err)
})

unbindFirebaseRef(key)

Only available inside of an enhanced action

Unbinds a bound firebase reference to a given property in the state.

unbindFirebaseRef('todos')

License

MIT

Support on Beerpay

Hey dude! Help me out for a couple of 🍻!

Beerpay Beerpay

vuexfire's People

Contributors

alex88 avatar bsaf avatar codeams avatar greenkeeper[bot] avatar hootlex avatar npmcdn-to-unpkg-bot avatar posva avatar psimyn avatar runeii avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vuexfire's Issues

An in-range update of vue is breaking the build 🚨

Version 2.2.6 of vue just got published.

Branch Build failing 🚨
Dependency vue
Current Version 2.2.5
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As vue is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details
Release Notes v2.2.6

Fixed

Commits

The new version differs by 6 commits .

  • 0cebdf5 [release] 2.2.6
  • 113fce9 [build] 2.2.6
  • 6fcfdbd warn and handle missing get in computed (fix #5265) (#5267)
  • 3209f6f remove parent/ref elm references when destroying instance, fix memory leak (fix vue-router#1279)
  • be07617 fix a typo (#5284)
  • 8a518c1 update sponsors and backers

See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Question: firebaseAction, bindFirebaseRef for filtered data

Hello everyone!
Not sure how to do it, maybe it's a common question.

I have one Document called applications and another called users.
As it's now, my application store retrieves all applications on the node using:

setApplicationsRef: firebaseAction(({commit, bindFirebaseRef, state}, {ref}) => {
    return new Promise((resolve, reject) => {
      bindFirebaseRef('applications', ref, {
        readyCallback: (val) => {
          resolve(val)
        }
      })
    })
  })

The thing is that i want to retrieve only the applications that belongs to a user.
My documents:

applications
  -KkLUGf4jE1Q1pSSQgAR
     name: "app01"
     users
       fmHILzHN7BgecvFJR1Tttey2hHI3: true


users
  fmHILzHN7BgecvFJR1Tttey2hHI3
    applications
      -KkLUGf4jE1Q1pSSQgAR: true
    email: "[email protected]"
    emailVerified: true
    name: "Lucas Gertel"
    photoUrl: "https://lh5.googleusercontent.com/-S7TveZd9tzM/..."
    uid: "fmHILzHN7BgecvFJR1Tttey2hHI3"

Thanks!

Stored Firebase reference converted to Observer on watch

I'm attempting to watch the state of one of my Firebase references, in order to trigger subsequent actions. Getting unexpected behavior where an action, dispatched from a watch callback, can no longer find the Firebase reference's methods. Instead, the object in the the store, rather than being a Firebase reference, has become an Observer object. Is this expected? Am I somehow losing the context by trigger an action from a component's watch?

[vuex] unknown mutation type: users/VUEXFIRE/objectValue

I have been banging my head against the wall trying to solve this yet-another issue I have developping with VuexFire. And the lack of documentation is not helping.

here is my main.js

export default new Vue({
  el: '#app',

  // As soon as possible initialize Firebase bindings with Auth and database
  beforeCreate () {
    auth()
      .onAuthStateChanged(user => {
        if (user) {
          // bind the app's currentUser to the firebase user of the same uid
          this.$bindAsObject('users.currentUser', database().ref(`users/${user.uid}`))

          // // bind the app's claims instance to firebase's claims/${uid}
          // this.$bindAsArray('claims', database().ref(`claims/${user.uid}`))
        } else {
          auth()
            .signInAnonymously()
            .catch(this.$handleError)
        }
      }).bind(this)
  },

  render: h => h(App),

  store // inject vuex into all components as this.$store
})

and below is the Vuex module definition for 'users'

const state = {
  currentUser: null
}

const getters = {
  currentUser: ({ currentUser }) => currentUser,
  isLoggedIn: ({ currentUser }) => !!currentUser
}

const mutations = moduleMutations('users')

export default {
  getters,
  namespaced: true,
  mutations,
  state
}

What I get when I run this code is [vuex] unknown mutation type: users/VUEXFIRE/objectValue and it seems the bad code section is this.$bindAsObject('users.currentUser', database().ref(users/${user.uid}))

I just want my local state 'currentUser' to be synced with the registered user of the same uid in the Firebase Realtime Database. Any help or redirection to some documentation would be welcome. Thank you.

unknown mutation type: VUEXFIRE/arrayAdd

Hey, with same code than my last issue (#30) but disabling strict mode, i have this error now:

vuex.js?90cb:430 [vuex] unknown mutation type: VUEXFIRE/arrayAdd
commit @ vuex.js?90cb:430
boundCommit @ vuex.js?90cb:389
(anonymous) @ vuexfire.js?e9e3:201
(anonymous) @ database.js?8254:167
ub @ database.js?8254:61
Rb @ database.js?8254:49
Sb @ database.js?8254:48
g.Gb @ database.js?8254:235
g.wd @ database.js?8254:211
Ce.wd @ database.js?8254:113
(anonymous) @ database.js?8254:111
fd @ database.js?8254:67
Ia.onmessage @ database.js?8254:66

I suspect than the mutation type should be called as raffles/VUEXFIRE/arrayAdd, but don't know why isn't working.

An in-range update of eslint is breaking the build 🚨

Version 3.13.1 of eslint just got published.

Branch Build failing 🚨
Dependency eslint
Current Version 3.13.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As eslint is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details
Release Notes v3.13.1
  • 3fc4e3f Fix: prefer-destructuring reporting compound assignments (fixes #7881) (#7882) (Teddy Katz)
  • f90462e Fix: no-extra-label autofix should not remove labels used elsewhere (#7885) (Teddy Katz)
Commits

The new version differs by 4 commits .

  • 7f8393c 3.13.1
  • 91883bf Build: package.json and changelog update for 3.13.1
  • 3fc4e3f Fix: prefer-destructuring reporting compound assignments (fixes #7881) (#7882)
  • f90462e Fix: no-extra-label autofix should not remove labels used elsewhere (#7885)

See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of eslint is breaking the build 🚨

Version 3.19.0 of eslint just got published.

Branch Build failing 🚨
Dependency eslint
Current Version 3.18.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As eslint is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
Release Notes v3.19.0
  • e09132f Fix: no-extra-parens false positive with exports and object literals (#8359) (Teddy Katz)
  • 91baed4 Update: allow custom messages in no-restricted-syntax (fixes #8298) (#8357) (Vitor Balocco)
  • 35c93e6 Fix: prevent space-before-function-paren from checking type annotations (#8349) (Teddy Katz)
  • 3342e9f Fix: don't modify operator precedence in operator-assignment autofixer (#8358) (Teddy Katz)
  • f88375f Docs: clarify that no-unsafe-negation is in eslint:recommended (#8371) (Teddy Katz)
  • 02f0d27 Docs: Add soda0289 to Development Team (#8367) (Kai Cataldo)
  • 155424c Fix: ignore empty path in patterns (fixes #8362) (#8364) (alberto)
  • 27616a8 Fix: prefer-const false positive with object spread (fixes #8187) (#8297) (Vitor Balocco)
  • 8569a90 Docs: add note about git's linebreak handling to linebreak-style docs (#8361) (Teddy Katz)
  • 5878593 Chore: fix invalid syntax in no-param-reassign test (#8360) (Teddy Katz)
  • 1b1046b Fix: don't classify plugins that throw errors as "missing" (fixes #6874) (#8323) (Teddy Katz)
  • 29f4ba5 Fix: no-useless-computed-key invalid autofix for getters and setters (#8335) (Teddy Katz)
  • 0541eaf Fix: no-implicit-coercion invalid autofix with consecutive identifiers (#8340) (Teddy Katz)
  • 41b9786 Fix: no-extra-parens false positive with objects following arrows (#8339) (Teddy Katz)
  • 3146167 Fix: eslint.verify should not mutate config argument (fixes #8329) (#8334) (alberto)
  • 927de90 Fix: dot-notation autofix produces invalid syntax for integer properties (#8332) (Teddy Katz)
  • a9d1bea Fix: comma-style autofix produces errors on parenthesized elements (#8331) (Teddy Katz)
  • d52173f Fix: don't generate invalid options in config-rule (#8326) (Teddy Katz)
  • 6eda3b5 Fix: no-extra-parens invalid autofix in for-of statements (#8337) (Teddy Katz)
  • 6c819d8 Fix: dot-notation autofix produces errors on parenthesized computed keys (#8330) (Teddy Katz)
  • 2d883d7 Fix: object-shorthand autofix produces errors on parenthesized functions (#8328) (Teddy Katz)
  • cd9b774 Fix: quotes false positive with backtick option in method names (#8327) (Teddy Katz)
  • d064ba2 Fix: no-else-return false positive for ifs in single-statement position (#8338) (Teddy Katz)
  • 6a718ba Chore: enable max-statements-per-line on ESLint codebase (#8321) (Teddy Katz)
  • 614b62e Chore: update sinon calls to deprecated API. (#8310) (alberto)
  • 0491572 Chore: use precalculated counts in codeframe formatter (#8296) (Vitor Balocco)
  • 8733e6a Chore: Fix incorrect error location properties in tests (#8307) (alberto)
  • c4ffb49 Chore: Fix typos in test option assertions (#8305) (Teddy Katz)
  • 79a97cb Upgrade: devDependencies (#8303) (alberto)
  • e4da200 Upgrade: Mocha to 3.2.0 (#8299) (Ilya Volodin)
  • 2f144ca Fix: operator-assignment autofix errors with parentheses (fixes #8293) (#8294) (Teddy Katz)
  • 7521cd5 Chore: update token logic in rules to use ast-utils (#8288) (Teddy Katz)
  • 9b509ce Chore: refactor space-before-function-paren rule (#8284) (Teddy Katz)
  • ddc6350 Fix: no-param-reassign false positive on destructuring (fixes #8279) (#8281) (Teddy Katz)
  • f8176b3 Chore: improve test coverage for node-event-generator (#8287) (Teddy Katz)
  • 602e9c2 Docs: fix incorrect selector examples (#8278) (Teddy Katz)
Commits

The new version differs by 38 commits .

  • 421aab4 3.19.0
  • 26a4dd5 Build: changelog update for 3.19.0
  • e09132f Fix: no-extra-parens false positive with exports and object literals (#8359)
  • 91baed4 Update: allow custom messages in no-restricted-syntax (fixes #8298) (#8357)
  • 35c93e6 Fix: prevent space-before-function-paren from checking type annotations (#8349)
  • 3342e9f Fix: don't modify operator precedence in operator-assignment autofixer (#8358)
  • f88375f Docs: clarify that no-unsafe-negation is in eslint:recommended (#8371)
  • 02f0d27 Docs: Add soda0289 to Development Team (#8367)
  • 155424c Fix: ignore empty path in patterns (fixes #8362) (#8364)
  • 27616a8 Fix: prefer-const false positive with object spread (fixes #8187) (#8297)
  • 8569a90 Docs: add note about git's linebreak handling to linebreak-style docs (#8361)
  • 5878593 Chore: fix invalid syntax in no-param-reassign test (#8360)
  • 1b1046b Fix: don't classify plugins that throw errors as "missing" (fixes #6874) (#8323)
  • 29f4ba5 Fix: no-useless-computed-key invalid autofix for getters and setters (#8335)
  • 0541eaf Fix: no-implicit-coercion invalid autofix with consecutive identifiers (#8340)

There are 38 commits in total. See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Support SSR for v2

Primarily objects
Arrays, maybe
docs to show the compatible way (using actions)

An in-range update of vue is breaking the build 🚨

Version 2.2.1 of vue just got published.

Branch Build failing 🚨
Dependency vue
Current Version 2.2.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As vue is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details
Commits

The new version differs by 3 commits .

See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

$bindAsArray Throws Vuex Outside Store Mutation Error

Hi all,

I am pretty sure I am the only one with this issue. I posted on StackOverflow but the system would not let me tag it properly with 'VuexFire'.

Here is my main.js where I declare the main VueJS app and its main components:

export default new Vue({
  el: '#app',

  // Binds app with Firebase servers as to always have the       currentUser
  beforeCreate () {
    auth()
      .onAuthStateChanged(user => {
        if (user) {
          // save the new user
          this.currentUser = user

          // get the required references to the Firebase database
          const currentUserRef = database().ref(`users/${user.uid}`)
          const claimsRef = database().ref(`claims/${user.uid}/`)

          // do the actual bindings from firebase to the vuex store
          this.$bindAsObject('users.currentUser', currentUserRef)
          this.$bindAsArray('claims.items', claimsRef) // <-- Here is the problem apparently

          // Make the binding references available on the root module
          this.currentUserRef = currentUserRef
          this.claimsRef = claimsRef
        } else {
          auth()
            .signInAnonymously()
            .catch(this.$handleError)
        }
      }).bind(this)
  },

  data: {
    claimsRef: null,
    currentUserRef: {},
    currentUser: null
  },

  render: h => h(App),

  router, // defines the main routing system in the app

  store // inject vuex into all components as this.$store
})

Binding as an Object is totally fine (no errors). But binding as an Array throws the following error:

VuexFire Error

Also, for reference, here is my corresponding Vuex module definition:

import { mutations as vuexMutations } from 'vuexfire'

const state = {
  items: null
}

const getters = {
  claims: ({ items }) => items
}

// Needed for VuexFire to automutate the bound claims items
const mutations = vuexMutations

export default {
  namespaced: true,
  mutations,
  state
}

An in-range update of uglify-js is breaking the build 🚨

Version 3.0.3 of uglify-js just got published.

Branch Build failing 🚨
Dependency uglify-js
Current Version 3.0.1
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As uglify-js is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details

Release Notes v3.0.3

Β 

Commits

The new version differs by 11 commits0.

  • aae7d49 v3.0.3
  • 0459af2 Update issue template: change harmony to uglify-es (#1900)
  • 04f2344 Remove unnecessary git clone instructions in README (#1897)
  • bad9d5c Change harmony to uglify-es in master README (#1895)
  • a0f5f86 gracefully handle non-Error being thrown (#1893)
  • 41996be extend test timeout
  • 5fd8244 v3.0.2
  • c14e280 print error stack in CLI (#1890)
  • bc3fa78 mention minify().error
  • 8c7c107 update minify() usage in test/ufuzz.js (#1888)
  • 3dd328d [3.x] fix documentation for beautify options (#1882)

false

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of firebase is breaking the build 🚨

Version 3.7.5 of firebase just got published.

Branch Build failing 🚨
Dependency firebase
Current Version 3.7.4
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As firebase is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details
Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Sources being unset and set to null when bound via function

Hi,

I have several single file components which use the same state variables. These components are linked between each other using vue-router.

Firebase is instantiated via function:

firebase: function() {
      var self = this;
      var startTime = 12345678;
      var tmpUid = 12345;
        return {
          overtimeBlocks: {
            source: db.ref('/overtime/' + tmpUid + '/blocks/').orderByChild("clockin").startAt(startTime),
            asObject: false
          },
          overtime: {
            source: db.ref('/overtime/' + tmpUid + "/").orderByChild("name"),
            asObject: false
          }
      }
}

And similarly (but with different parameters) in another component.

When routed between components, the state variable correctly loads each array element (shown within Vue-DevTools, but then is sent a "VUEXFIRE/objectValue" with a payload of {Key: "overtime", Record: null} which obviously sets the state variable to null and removes the loaded firebase data array.

Has anyone else experienced similar?

Many thanks,
Jake.

Thoughts on vuexfire for larger project

Its finally a day off and I'm diving into vuexfire, awesome! Something that throws me off right away is this line in the readme, "Everything else works just as vuefire. Refer to its readme for more documentation."

Likely vuexfire is very well put together but I'm trying to comprehend it in terms of my real life project. It looks like the snippet examples are scattered around and assume a lot of knowledge of firebase and jumping around between multiple repos.

What would be most helpful is if what vuexfire does would be added to the nice diagram that vuex already provides and a comprehensive guide could be put together. I can definitely help with suggestions along with other vuexfire users.

Maybe some details on how the binding to firebase actually works behind the scenes can be provided? Then some more clarity on the firebase refs vs the store module state and why it is necessary to declare things twice to achieve the binding. Some more complete well commented examples would help.

In the end I will need a global store that has ten modules. The state for these modules is already defined as JSON documents on firebase. The documents are not just simple counter values and such, instead they are large nested trees of values expressed as objects and arrays. What is not clear to me is if I need to re-declare all that nested data on the vuex side of things again?

If I have so much data in each document how am I suppose to bind this to a vuex store? Can I bind the complete document or bind to any part of it or can I instead just grab the aspects of it I need further down the component flow?

Sorry for all the questions but between needing to get a project setup, various ways to define a global store of modules and unclear firebase binding details I'm feeling that my free day is slipping way :)

P.S. It would be great if the older Vue v1 stuff could be extracted into it's own readme.

Vue-cli

Hi, just a thought - with 2.0 around the corner, I thought it would be very cool to have a Webpack template for Vue 2.0 with Vuex/Vuexfire & Firebase setup and pre-configured (possibly with Bootstrap 4 included) as I can certainly see myself using this stack a lot more and would like to be able to get up and going very quickly for each new app.

Is this something you'd be interested in, or am I best to just fork the Webpack template and create something for my own needs? Obviously this isn't the correct repo (Webpack template for Vue-cli), but wanted to run it by you first.

Thanks in advance.

Dynamic binding

Suppose I have an index of users in a group:

group: {
  user1: true,
  user7: true,
  user15: true,
  etc...
}

I want to bind references to each of these users to the store:

for (const userKey in group) {
  this.$bindAsObject('users.${userKey}', db.ref('users/${userKey}'))
}

It seems that it's not possible. Is there anything I can do instead?

VuexFire.moduleMutations not working properly

so i have this code in my users module

import VuexFire from 'vuexfire'

const state = {
  auth: null,
  user: null,
  current_user: null,
  foundUser: null,
  users: null,
};

const getters = {
  getFoundUser(state) {
    return state.foundUser;
  }
};

const mutations = VuexFire.moduleMutations('users');

const actions = {
  addUser({rootState},user) {
    if(!user) return;
    rootState.refs.users.push(user);
  },
  deleteUser({rootState},user) {
    if(!user) return;
    rootState.refs.users.child(user['.key']).remove();
  },
  updateUser({rootState},user) {
    if(!user) return;
    rootState.refs.users.child(user['.key']).update(user);
  },
  getUserBy({state,rootState},{by,value}) {
    _.find(rootState.users,[by,value]);
  }
};
//called by this.$store.dispatch('addUser')
export default {
  state,
  getters,
  mutations,
  actions
}

and use it on my root store instance
this is just an object and will be converted to on the main js

const store = {
  state: {
    refs: null,
  },
  // modules: {
  //   stores,
  //   items,
  //   users,
  //   managers,
  //   employees,
  //   customers,
  //   transactions,
  // },
  mutations:  { ['SET_REFS'](state,payload){
    state.refs = payload;
  }},
  // mutations: Object.assign({},VuexFire.mutations,{
  //   ['SET_REFS'](state,payload) {
  //     state.refs = payload;
  //   }
  // })

};

export default store

then import that root store on my main js

and do store.registerModule

if i dont do that it replaces my users module states all of it

import VuexStore from './vuex';

import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import VuexFire from 'vuexfire'
import App from './App.vue';
import VuexStore from './vuex';
import { sync } from 'vuex-router-sync';
import routes from './routes';
import firebase from 'firebase';
import db from './firebase_config';
import VueMaterial from 'vue-material'
import 'vue-material/dist/vue-material.css'

import users from './vuex/modules/users'
import items from './vuex/modules/items'
import stores from './vuex/modules/stores'
import managers from './vuex/modules/managers'
import employees from './vuex/modules/employees'
import customers from './vuex/modules/customers'
import transactions from './vuex/modules/transactions'

Vue.use(Vuex);
Vue.use(VueRouter);
Vue.use(VuexFire);
Vue.use(VueMaterial)

Vue.material.theme.register('default', {
  primary: 'blue',
  accent: 'teal'
})

const store = new Vuex.Store(VuexStore);
store.registerModule('users',users)
const router = new VueRouter({
  mode: 'history',
  routes,
});

sync(store, router);

const app = new Vue({
  router,
  store,
  firebase: {
    users: db.ref('users'),
    // items: db.ref('items'),
    // stores: db.ref('stores'),
    // managers: db.ref('managers'),
    // employees: db.ref('employees'),
    // customers: db.ref('customers'),
    // transactions: db.ref('transactions'),
  },
  render: h => h(App),
  beforeCreate() {
    if(!this.$store.state.refs) {
      this.$store.commit('SET_REFS', this.$firebaseRefs);
      // this.$store.dispatch('deleteUser', {['.key']: '-KXIgd1C7L_F5UVZ-oAM'});
    }
  }
}).$mount('#app');

and error pops out on the console

image

i dont know if my setup is right or its a bug

VuexFire 2

Following recent issues #12, #13 and #9, I've been thinking about how vuexfire API should be in the future. Now, I know the v1 is not even out but the idea is to make the current version a v1 with the least possible amount of breaking changes and adding deprecations for v2.
In v2, support for Vue 1, Vuex 1 and Firebase 2 will be dropped while v1 would still be supporting them all.

What is wrong with the current API

There are many things that aren't currently optimal and that I'd like to address in v2

Double efforts to bind a reference

ATM you have to declare a variable in the state and also tell vuexfire what's the firebase reference that should go there:

// store.js
const state = {
  items: null // binded later
}
// some-view.vue
firebase: {
  items: db.ref('items')
}

This is actually not needed because I can just do Vue.set(state, key, value) and the data will be reactive, which was the problem I was facing in the first time. I tried it and works fine at least for Vue 2.
However, this also makes it harder to see how the state is built, since you cannot just check store.js (or any other module) and walk through the state variable. Your state is spread all around your app, which is not convenient.
I therefore think making the user declare the state is a good thing but I should not force that unless it is the only way.

Using firebase option makes no sense

Initially the firebase option was taken from vuefire, however, it doesn't make sense having to use a Vue instance to bind the references to the Vuex store.
In the current state, it's very easy to migrate from vuefire to vuexfire but you cannot use both at the same time which makes sense in very specific situations.

Binding, unbinding should be doable out of a vm instance. In other words vuexfire should expose functions for this purpose and not add any extra method to the Vue prototype.

What I think would be a good new API for vuexfire

Removing the firebase option to declare references binding alongside all the methods/variables added to the Vue prototype ($bind, $unbind, $firebaseRefs).
This will allow vuefire to work at the same time that vuexfire.

Installing VuexFire as usual:

// main.js
Vue.use(Vuex)
Vue.use(VuexFire)

// store.js
import { generateMutations } from 'vuexfire'

var sore = new Vuex.Store({
  state: {
    list:  null
  },
  mutations: {
    ...mutations,
    ...generateMutations() // Pass the module name as an argument
  }
})

Exposing those as methods:

import { bind, refs } from 'vuexfire'

setListRef ({ commit, state }, { listRef }) {
  // The current state may have another ref binded
  // state === { list: [...] } 
  // the bind method needs access to the commit and a key to bind on the state
  const unbind = bind(commit, 'list', listRef)
  // VuexFire will internally get the path from the ref and save it
  // so you can later on access it

  // call unbind() if you manually want to unbind
}

// You still don't need an action but here's an example
// using one
addToList (context, { item }) {
  // Giving the path of the ref was 'items'
  // It could have been 'users/someUser/list'
  refs('list').push(item)
}

Notice how you no longer specify the module you're binding to because the bind method use a commit function that is bound to the module you're working with. Internally a reference to the commit function is saved so calling bind again on the same key within the same module will unbind a previously bound reference.

Since VuexFire is no longer aware of the module you're working in, you cannot use a method like unbind('cart.items') to unbind the key items of the module cart. This should not be a problem since unbinding is done automatically when binding a new value and since you can always dispatch an action to call the unbind method.

If the user manually register any module then, he would also have to manually unbind any refs used by that module when unregistering it.

Please, share your thoughts on this πŸ˜„

Better place to use "query's"?

Hello!
I'm with a question about the best pratice when using vuexfire.

Where's the best place to put logic like this one:

        let appsRef = db.ref('applications')
        let connectorsRef = db.ref('connectors')
        let appConnectorsRef = appsRef.child(this.$route.params.id).child('connectors')
        appConnectorsRef.on('child_added', (snap) => {
          connectorsRef.child(snap.key).once('value', (snap) => {
            console.log(snap.val())
          })
        })

I have one application module that already used bindFirebaseRef to initialize data, and now I'm using this code inside a method component.

Not sure if this kind of thing should be added as a getter in my module or something like that.
Can you help me with this?

Ty!

Where to put moduleMutations()?

I'm testing the new modules update and am having some trouble.

EDIT: I think I may be misunderstanding how vuexfire works with mutations. Does it automagically make them for us?

I'm getting the error:
image

Here's the lay of the land:

/vuex/modules/auth/actions.js

import firebase from '../../../services/firebase.js'

import { AUTHENTICATE } from './mutation-types';

export function fetchUser ({ commit }) {
  return firebase.auth.onAuthStateChanged((user) => {
    commit(AUTHENTICATE, user);
  });
}

/vuex/modules/auth/getters.js
export const getAuth = state => state.user

/vuex/modules/auth/index.js

import * as actions from './actions';
import * as getters from './getters';

import { AUTHENTICATE } from './mutation-types'

const initialState = {
  user: null
}

const mutations = {
  [AUTHENTICATE] (state, user) {
    state.user = user
  },
}

export default {
  state: { ...initialState },
  actions,
  getters,
  mutations,
}

/vuex/modules/auth/mutation-types.js
export const AUTHENTICATE = 'auth/AUTHENTICATE';

/vuex/modules/store.js

import Vue from 'vue'
import Vuex from 'vuex'
import VuexFire from 'vuexfire'

import auth from './modules/auth'
import games from './modules/games'

Vue.use(Vuex)
Vue.use(VuexFire)

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  modules: {
    auth,
    games,
  },
  strict: debug,
})

App.vue

  export default {
    components: {
      AppNav
    },
    created () {
      this.$store.dispatch('fetchGames');
      this.$store.dispatch('fetchUser');
    }
  }

The only thing I'm able to find is that with I'm supposed to use mutations: VuexFire.moduleMutations('items') somewhere if I'm using modules, and I'm not sure where though in a setup like this.

An in-range update of vue is breaking the build 🚨

Version 2.2.5 of vue just got published.

Branch Build failing 🚨
Dependency vue
Current Version 2.2.4
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As vue is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details
Release Notes v2.2.5

Fixed

Commits

The new version differs by 19 commits .

  • c0ad75b [release] 2.2.5
  • b876395 [build] 2.2.5
  • bfeb28f pin todomvc css version
  • 3b7cfc7 coverage
  • f4630d0 treat with different types as different nodes (fix #5266)
  • 5222f06 bump deps
  • 6de1b9b optimize patch conditionals
  • 0bb529a also warn when listening to camelCase events in in-DOM templates
  • e47b1e5 Allow named properties on reactive arrays. (#5216)
  • 70db229 handle v-model on password input field on ie9 (fix #5250) (#5253)
  • 23a058e fix(inject): change warn message when trying to mutate an injected value (#5243)
  • 7dea9f1 fix provide isn't reactive with a single array (#5229)
  • 4c4a2ab trigger event after reassigned state - Fix #5191 (#5233)
  • e733e5c fix SSR v-show render. (#5224)
  • 84856a3 update issue template

There are 19 commits in total. See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of vue is breaking the build 🚨

Version 2.3.3 of vue just got published.

Branch Build failing 🚨
Dependency vue
Current Version 2.3.2
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As vue is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details

Release Notes v2.3.3

Fixed

  • #5586 fix unecessary input trigger with v-model on change event (@posva via #5589)
  • #5591 ssr template interpolation should be whitespace-insensitive (@HerringtonDarkholme via ##5597)
  • #5592 fix regression where text nodes are merged into comment placeholder nodes (@maggiehe via #5593)
  • #5610 fix Vue.use not chainable when plugin has already been installed, also makes Vue.mixin chainable. (@lzxb via #5610)
  • #5615 fix scoped slots when used together with v-for
  • #5618 fix slot elements after v-for being unnecessarily recreated (@gebilaoxiong via #5627)
  • #5633 fix comment nodes not cloned properly (@pengchongfu via #5633)
  • #5635 fix async components timeout triggered when already resolved
Commits

The new version differs by 19 commits0.

  • 8d56a49 [release] 2.3.3
  • 6bdaeb0 [build] 2.3.3
  • aaad733 improve scoped slot test case (#5640)
  • e70f191 no need to test composition events on Android
  • 38759a6 fix test case in IE
  • 8d54aec async components: timeout should not trigger if already resolved (fix #5635)
  • 3139605 ignore ssr getter
  • 0ccefff support v-for on scoped slots (fix #5615)
  • dc00590 comments
  • ec70b44 tweak noramlizeArrayChildren
  • f2bd882 Fix: nested child elements can not be updated correctly, fix #5618 (#5627)
  • 5d965d5 clone isComment when cloneVNode (#5633)
  • b5b1ac3 improve mutli-line && coding style to keep consistence (#5625)
  • 1c40e32 Fix use mixin API feat continuous operation (#5610)
  • ca02043 avoid using native as identifier (close #5623)

There are 19 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Support Modules

Currently, vuexfire only let you declare refs in the state.
In bigger applications, you may need to to use modules.

An in-range update of vue is breaking the build 🚨

Version 2.2.4 of vue just got published.

Branch Build failing 🚨
Dependency vue
Current Version 2.2.3
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As vue is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details
Commits

The new version differs by 3 commits .

  • 2343b90 [release] 2.2.4
  • 6cf5d2d [build] 2.2.4
  • 45e273f fix perf measure regression for nested components of the same name (fix #5181)

See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

vuexfire and vuefire

I have this instance happening where I only want data from firebase in the store. When I have another component binding something from Firebase:

firebase: {
   users: firebase.database().ref('users')
}

I do not have this defined in the store but the store is asking for it:
database.js?8254:60Uncaught Error: VuexFire: bind failed: "users" is not defined

Is there a way to still use firebase in some components with vuefire but not have them bound to the store?

How to get feedback when database is loading?

I like vuexfire very much. What I wanted was to have a loading gif show when the database is waiting to be loaded. I tried using the readyCallback but it is not working. When the store is loaded, it doesn't call the readyCallback function. what am I missing.

An in-range update of eslint-plugin-html is breaking the build 🚨

Version 2.0.2 of eslint-plugin-html just got published.

Branch Build failing 🚨
Dependency eslint-plugin-html
Current Version 2.0.1
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As eslint-plugin-html is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Struggling to Identify Best Practice

I'm struggling to identify ways to keep vuefire and vuexfire DRY.

It appears in order to perform operations like add, remove, update I need access to a database reference for the objects. It doesn't appear I can use vuexfire like vuex in the sense that I can dispatch actions and commit mutations to alter them. Am I right in thinking the best way to keep things clean is to create a module that contains an instance of each type of ref I need and export them to make them available.

Additionally, I can't seem to find a way to access user specific database references?

I tried to create a callback that would change my references after auth but these all fail with the error
vue.common.js?e881:435 Error: VuexFire: invalid Firebase binding source.

readme missing Vuex script

<head>
    <!-- Vue -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <!-- Firebase -->
    <script src="https://gstatic.com/firebasejs/3.5.2/firebase.js"></script>
    <!-- VuexFire -->
    <script src="https://unpkg.com/vuexfire/dist/vuexfire.js"></script>
  </head>

should be

<head>
    <!-- Vue -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <!-- Firebase -->
    <script src="https://gstatic.com/firebasejs/3.5.2/firebase.js"></script>
    <!-- Vuex -->
    <script src="https://unpkg.com/vuex/dist/vuex.js"></script>
    <!-- VuexFire -->
    <script src="https://unpkg.com/vuexfire/dist/vuexfire.js"></script>
  </head>

yeah?

Provide doc about integrating in bigger projects

As seen in #5 and other requests, it'll be great to get further guidance and best practices about how to use firebase with vuexfire

  • Where to bind references (actions)
  • Where should the actual bound called (where to dispatch actions)
  • where to host references
  • How to write tests

Feel free to share your thoughts on this about what you'll like to see

vuexfire and mutations

These two things seem to be at odds and it's making it hard for me to understand how I should be trying to structure my code:

  1. The Vuex docs state, "The only way to actually change state in a Vuex store is by committing a mutation."

  2. The Vuexfire TodoApp addTodo() method uses $firebaseRefs.items.push() to create records.

I would have guessed there to use something like: store.commit('addTodo', <payload>) or, from what I'm reading, I guess that should even be pushed through an action rather than a mutation.

Although … shouldn’t addTodo()’s Firebase work be done in an action and based on its success/failure trigger a mutation?

That seems close to the use case described in the Vuex Actions docs under the Dispatching Actions section at the code sample with header: β€œA more practical example of real-world actions ... which involves calling an async API and committing multiple mutations:”

State management responsibilities

I'm just starting to investigate Vuexfire, and trying to understand best implementation practices. In the example todo app, you're making updates directly to Firebase references from an app method. This strikes me as somewhat of an anti-pattern, since the whole idea of Vuex is to separate concerns, and manage state reactively by triggering actions/mutations on the store.

So it's almost like your Firebase db becomes a second/parallel state manager, and your Vuex store reacts to changes to the db, through which other collaborator Vue components can respond accordingly.

I'm wondering if, rather than triggering changes to Firebase from component methods, it would be better to create mutations/actions on the Vuex store that call Firebase reference methods. This would keep individual components agnostic to the database layer and put all state management responsibilities (including persisting changes to the database) in the Vuex layer.

Example:

// store.js
import Vue from 'vue';
import Vuex from 'vuex';
import { firebaseMutations, firebaseAction } from 'vuexfire';

Vue.use(Vuex);

const db = firebase.initializeApp(firebaseConfig).database();

const refs = {
  counter: db.ref('counter')
};

export default new Vuex.Store({
  state: {
    counter: {
      increment: 0
    }
  },
  getters: {
    counter (state) {
      return state.counter.increment;
    }
  },
  mutations: {
    increment (state) {
      refs.counter.set({
        increment: state.counter.increment + 1
      });
    },
    ...firebaseMutations
  },
  actions: {
    setCounterRef: firebaseAction(({bindFirebaseRef}, ref) => {
      bindFirebaseRef('counter', refs.counter);
    })
  }
});


// App.Vue
<template lang="pug">
  div.app
    button(v-on:click="increment") Increment
    span.counter {{ counter }}
</template>

<script>
import Vuex from 'vuex';

export default {
  methods: {
    increment () {
      this.$store.commit('increment');
    }
  },
  computed: {
    counter () {
      return this.$store.getters.counter;
    }
  }
}
</script>


// app.js
import App from './App.vue';
import store from './store.js';

new Vue({
  el: '#cohear',
  store,
  render: h => h(App),
  created() {
    this.$store.dispatch('setCounterRef');
  },
});

Allow vuex strict mode

Hi!

Was trying to make this works on my project with no success. I have multiple modules on my store and have modules on different files, my code is like as follow

store/index.js

import VuexFire from 'vuexfire'
import * as actions from './actions'
import * as getters from './getters'

... // HERE I IMPORT SOME OTHERS MODULES

import raffles from './modules/raffles'

Vue.use(Vuex)
Vue.use(VuexFire)

const store = new Vuex.Store({
  strict: true, 
  actions,
  getters,
  modules: {
    ... // HERE I ADD THE OTHERS MODULES
    raffles
  },
  state: {
  },
  mutations: {
  }
})

export default store

store/modules/raffles.js

import VuexFire from 'vuexfire'

const state = {
  raffles: null
}

const mutations = VuexFire.moduleMutations('raffles')

export default {
  state,
  mutations
}

app.js

import Vue from 'vue'
import * as firebase from 'firebase'
import store from './store'
import { sync } from 'vuex-router-sync'
import App from './App'

// Initialize Firebase
var config = {
  apiKey: process.env.FIREBASE_API_KEY,
  authDomain: process.env.FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_DATABASE_URL,
  storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID
}
const firebaseApp = firebase.initializeApp(config)
const db = firebaseApp.database()

const app = new Vue({
  store,
  ...App,
  firebase: {
    raffles: db.ref('raffles')
  }
})

export { app, store, firebaseApp }

I don't know why i am getting this full error on the console:

[Vue warn]: Error in watcher "state" 
(found in root instance)
warn @ vue.common.js?e881:521
vue.common.js?e881:3027 Uncaught Error: [vuex] Do not mutate vuex store state outside mutation handlers.
    at assert (eval at <anonymous> (app.js:904), <anonymous>:214:27)
    at Vue$3.store._vm.$watch.deep (eval at <anonymous> (app.js:904), <anonymous>:755:5)
    at Watcher.run (eval at <anonymous> (app.js:796), <anonymous>:3017:19)
    at Watcher.update (eval at <anonymous> (app.js:796), <anonymous>:2991:10)
    at Dep.notify (eval at <anonymous> (app.js:796), <anonymous>:580:13)
    at Object.reactiveSetter [as raffles] (eval at <anonymous> (app.js:796), <anonymous>:810:11)
    at Object.initWithValue (eval at <anonymous> (app.js:1391), <anonymous>:475:17)
    at bindAsArray (eval at <anonymous> (app.js:1391), <anonymous>:196:15)
    at bind (eval at <anonymous> (app.js:1391), <anonymous>:180:6)
    at Vue$3.created (eval at <anonymous> (app.js:1391), <anonymous>:336:8)

Thanks and any helps will be appreciated.

Promise not working

I'm doing something #wrong.
I have this code on my store, but when retrieving from my component the then in dispatch is called before the callback.

On my component:

methods: {
      fetchData() {
        this.loading = true
        this.$store.dispatch('setApplicationsRef').then(response => {
          console.log('data dne')
          this.loading = false
        })
      }
    }
And on my module:

const actions = {
  setApplicationsRef: firebaseAction(({commit, bindFirebaseRef, state}) => {
    return new Promise((resolve, reject) => {
      bindFirebaseRef('applications', applicationsRef, {
        readyCallback: () => {
          resolve()
        }
      })
    })
  })
}

The console.log('data dne') is getting called before the resolve on actions

Question: Iterating children of a mapped firebase reference

I'm wrestling a bit with how best to manage the 'extra' info that vue and vuexfire create on state objects. I have an object mapped to a firebase reference called 'groups' which might contain zero or more 'group' records. Obviously with FB, you can't have a key with no value, so the key itself isn't even present when there are zero groups. In this case, the mapped vuexfire obejct looks like this:

console.log(Reflect.ownKeys(state.groups))
(3) [".value", ".key", "__ob__"]

If I then create a group called test, the result is as below:

console.log(Reflect.ownKeys(state.groups))
(3) ["test", ".key", "__ob__"]

So, calculating the number of groups is problematic (can't use .length of the Reflect call directly), and iterating using v-for is also tricky as it pulls out the vuexfire .key and .value properties if they're there (I'm presuming .value is only there if the reference is 'empty' as a placeholder? Or does it serve some other purpose?).

Do you have any advice or best ways of doing this with vuexfire? Or would you consider adding any helpers to vuexfire to make it easy to use mapped objects with v-for, count how many child nodes there are, etc.?

vuex fire mutation problem

Hi thanks so much for making this library, however i have a small problem with the vuexfire mutation. I get this error:
[vuex] unknown mutation type: VUEXFIRE_ARRAY_INITIALIZE and unknown mutation type: vuexfire/ARRAY_ADD:
Here is my store.js:

`import Vue from 'vue'
import Vuex from 'vuex'
import { firebaseAction, firebaseMutations } from 'vuexfire'

Vue.use(Vuex)

const store = new Vuex.Store({
  strict: true,
  state: {
    projects: [],
    items: [],
  },
  actions: {
    setItemsRef: firebaseAction(({ bindFirebaseRef }, ref) => {
      bindFirebaseRef('items', ref)
    }),
  },
  mutations: {
    firebaseMutations,
  },
  getters: {
    compconstedProjects: state => state.projects.filter(project => project.compconsted).length,
    projectCount: state => state.projects.length,
  },
})
export default store`

and in my component I am calling the action setItemsref like this:

export default {
  computed: mapState([
    'items',
  ]),
  created() {
    this.$store.dispatch('setItemsRef', ref)
  },
}

An in-range update of firebase is breaking the build 🚨

Version 3.6.5 of firebase just got published.

Branch Build failing 🚨
Dependency firebase
Current Version 3.6.4
Type peerDependency

This version is covered by your current version range and after updating it in your project the build failed.

As firebase is β€œonly” a peerDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details
Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

VuexFire getting undefined with vue-cli?

I'm having some trouble getting off the ground with vuexFire. Here's my project It is a webpack-simple build from vue-init with a pretty bare bones example at the moment.

note the src/store directory.

When I npm run dev this, I get an error:

vuex.js?90cb:373 Uncaught TypeError: plugin is not a function
    at eval (eval at <anonymous> (http://localhost:8080/dist/build.js:1008:1), <anonymous>:373:68)
    at Array.forEach (native)
    at new Store (eval at <anonymous> (http://localhost:8080/dist/build.js:1008:1), <anonymous>:373:33)
    at eval (eval at <anonymous> (http://localhost:8080/dist/build.js:907:1), <anonymous>:30:13)
    at Object.<anonymous> (http://localhost:8080/dist/build.js:907:1)
    at __webpack_require__ (http://localhost:8080/dist/build.js:660:30)
    at fn (http://localhost:8080/dist/build.js:84:20)
    at eval (eval at <anonymous> (http://localhost:8080/dist/build.js:1053:1), <anonymous>:4:71)
    at Object.<anonymous> (http://localhost:8080/dist/build.js:1053:1)
    at __webpack_require__ (http://localhost:8080/dist/build.js:660:30)

This happens to be at plugins: [VuexFire.default] in my new Vuex.Store
So I put a console log above it to check it out:
console.log('VuexFire: '+JSON.stringify(VuexFire), 'Vuex:'+JSON.stringify(Vuex))

This produces:

VuexFire: undefined Vuex:{"version":"2.1.1","installed":true}

even though both are installed and imported.

How to use with large database?

I am trying to use this for a blog site, while I was prototyping everything worked great.. until I imported my dataset, only about 6000 posts.

Is there something better I could do? As soon as this wakes up it starts pulling from the root of the '/posts' and my chrome memory usage shoots up to 1.6GB.

If I do the .limitToFirst(30) I am able to run fine again, but then I cannot get more posts.

Thank you!

import lodash from 'lodash';
import { firebaseMutations, firebaseAction } from 'vuexfire';
import { fbAppAuth } from 'src/fbase'
// Swap these comments for debug server.
// import { fbApp } from 'src/fbase'
// const db2 = fbApp.database();
// const postsRefDebug  = db.ref('zzPosts');
const db2 = fbAppAuth.database();
const postsRef  = db2.ref('posts').limitToFirst(30);

const postsModule = {
    state: {
        posts: []
    },
    getters: {
        getPosts(state) { return state.posts; },
        // upvotedPosts(state) { return state.posts.filter(post => post.votes > 0) }
    },
    actions: {
        setPostsRef: firebaseAction((context, ref) => { context.bindFirebaseRef(`posts`, ref); }),
        addpost({ commit }, params) { commit('ADD_POST', params) },
        removepost({ commit }, key) { commit('REMOVE_POST', key) },
        upvotepost({ commit }, key) { commit('UPVOTE_POST', key) },
    },
    mutations: lodash.merge(firebaseMutations, {
        ADD_POST(state, payload) {
            postsRef.push(payload);
        },
        REMOVE_POST(state, key) { // TODO if I am the owner
            if(!key)
                return;
            postsRef.child(key).remove();
        },
        UPVOTE_POST(state, key) {
            if(!key)
                return;
            const theDataRef = postsRef.child(key)
            theDataRef.once('value', (snapshot) => {
                theDataRef.update({
                    votes: snapshot.val().votes + 1
                })
            })
        },
        // ...firebaseMutations
    }),
    methods: {
        /**
        * @function {init} optional function. This is called by the store on load
        * @param  {string} store      {The store instance. This is the store passing itself in to this function}
        * @param  {string} importName {The name that this module was imported as. Necessary to dispatch actions to the store. }
        */
        init(store, importName) {
            const iname = importName || `posts`;
            store.dispatch(`${iname}/setPostsRef`, postsRef);
            // console.log(`posts init called! ${postsRef}`)
        }
    },
    /**
     * @param {bool} namespaced - please always keep include this. THis will namespace this module on the outside.
    */
    namespaced: true
}

export default postsModule;

Waiting for data load.

I need to return a promise from my action.
Not sure how to do it, can someone help me?

This do not works as I usually do with Vuex

const actions = {
  setApplicationsRef({commit, state}) {
    return new Promise((resolve, reject) => {
      const testing = firebaseAction(({ bindFirebaseRef }, { ref }) => {
        bindFirebaseRef('todos', ref, {readyCallback: () => {
            resolve()
        }})
      })
    })
  }
}

Question: effective 2-way binding between vuex store and firebase

I've got the basic setup working in that the state is bound to a firebase reference, and changes to the firebase are immediately reflected in the app.

I would like the app (components) to not really know anything about firebase though, and I had originally assumed that changing the state bound to firebase would also trigger updates to firebase. But I guess not - looking at the source it looks like it's only listening for firebase updates, not also making firebase writes.

Do you have plans to make vuexfire work in both directions?

If not, I guess I would need to write to firebase in the store actions - is that a good (or best) place to do it? Is there an existing pattern for replicating state changes back to firebase?

Tx

An in-range update of vue is breaking the build 🚨

Version 2.2.3 of vue just got published.

Branch Build failing 🚨
Dependency vue
Current Version 2.2.2
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As vue is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details
Release Notes v2.2.3

Notable Changes

  • Vue.config.performance now defaults to false due to its impact on dev mode performance. Only turn it on when you need it.

Improvements

  • Now warns usage of camelCase props when using in-DOM templates. (@CodinCat via #5161)
  • Now warns when template contains text outside of root element. (@xujiongbo via #5164)

Fixed

  • #5121 parse content in textarea as plaintext (@HerringtonDarkholme via #5143)
  • #5146, #5169, #5171 fix v-on .prevent modifier regression when combined with other key modifiers (@Kingwl via #5147)
  • #5150 v-bind object should have lower priority than explicit bindings
  • #5162 fix custom directive argument fallthrough
  • #5174 fix ever-increasing component render time caused by calls to performance.measure in dev mode.
Commits

The new version differs by 16 commits .

  • d185dd2 [release] 2.2.3
  • b28aa39 [build] 2.2.3
  • 368a335 perf code coverage
  • 0416839 improve camelCase prop warning message
  • c6ab2e0 warn when template contains text outside root element (#5164)
  • 025e763 Warn when not passing props in kebab-case (#5161)
  • 4d227b9 turn off perf timeline measuring by default + reduce its impact on dev time perf (fix #5174)
  • a6e1ae0 v-bind object should have lower priority than explicit bindings (fix #5150)
  • e7dfcc3 fix custom directive arg fall through (fix #5162)
  • 0b964c8 formatting tweaks
  • 045ff5d refactor create-component
  • 4964b25 fix wrong order of generate modifier code (#5147)
  • f9706dc fix v-on unit test (#5144)
  • 8fca83d fix #5121: parse content in textarea as plaintext (#5143)
  • 82bc8b7 Merge branch 'dev' of github.com:vuejs/vue into dev

There are 16 commits in total. See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Vuex Issue

I tried adding this after scaffolding a project with Vue-cli (using webpack#2.0), but I get the following error in the browser console after following the docs.

Uncaught TypeError: _vuexfire2.default.mapGetters is not a function

Please advise, thanks.

Unable to get working correctly

Hi @posva - best to open an issue here. Myself and @microcipcip are having issues getting Vuexfire working correctly in a typical Webpack setup.
I have provided an example repo here. This should connect straight to my Firebase database, you can see the Vuex store populate with the data from Firebase, however, it is not updating the DOM.

Would you mind taking a look please, so that we can provide a solid example for others looking to use Vuexfire with a project generated with Vue-CLI?

Thanks in advance.

VuexFire 2 Example?

put both in to vuex folder

firebase-config.js

import * as firebase from 'firebase'

firebase.initializeApp({
  apiKey: "AIzaSyD51nbaS-M9rE4iud3bbJEZSvfcNwt4b4g",
  authDomain: "eclipse-5f86e.firebaseapp.com",
  databaseURL: "https://eclipse-5f86e.firebaseio.com",
  storageBucket: "eclipse-5f86e.appspot.com",
  messagingSenderId: "99048529317"
});

export default firebase;
import firebase from './utils/firebase-config'

function indexForKey(array, key) {
  return array.findIndex(element => element['.key'] == key);
}

function createRecord(snapshot) {
  let data = snapshot.val();
  data['.key'] = snapshot.key;
  return data;
}

function runFirebaseEvents(key, store) {

  let ref = store.getters[`$${key}`];

  let records = store.getters[key];

  ref.on('child_added', function (snapshot, prevKey) {
    let index = prevKey ? indexForKey(records, prevKey) + 1 : 0;
    let record = createRecord(snapshot);
    record['.ref'] = key;
    store.commit(`${key}/ADDED`, {index, record});
  });

  ref.on('child_changed', function (snapshot) {
    let index = indexForKey(records, snapshot.key);
    let record = createRecord(snapshot);
    record['.ref'] = key;
    store.commit(`${key}/CHANGED`, {index, record});
  });
  ref.on('child_removed', function (snapshot) {
    let index = indexForKey(records, snapshot.key);
    store.commit(`${key}/REMOVED`, {index});
  });
  ref.on('child_moved', function (snapshot, prevKey) {
    let index = indexForKey(records, snapshot.key);
    let newIndex = prevKey ? indexForKey(records, prevKey) + 1 : 0;
    newIndex += index < newIndex ? -1 : 0;
    store.commit(`${key}/MOVED`, {newIndex, index});
  });

}

function generateMutations(key) {
  return {
    [`${key}/ADDED`](state, {index, record}) {
      state[key].splice(index, 0, record)
    },
    [`${key}/CHANGED`](state, {index, record}) {
      state[key].splice(index, 1, record)
    },
    [`${key}/REMOVED`](state, {index}) {
      state[key].splice(index, 1);
    },
    [`${key}/MOVED`](state, {newIndex, index}) {
      const array = state[key];
      const data = array.splice(index,1)[0];
      array.splice(newIndex,0,data);
    }
  }
}

function generateGetters(key) {
  return {
    [`$${key}`](state) {
      return state[`$${key}`];
    },
    [key](state) {
      return state[key];
    }
  }
}

function generateState(key) {
  return {
    [`$${key}`]: firebase.database().ref(key),
    [key]: []
  }
}

export function VuexFireSync(key) {
  return {
    state: {
      ...generateState(key)
    },
    mutations: {
      ...generateMutations(key)
    },
    getters: {
      ...generateGetters(key)
    }
  }
}
export function VuexFireActions() {

  return {
    VuexFireSave({getters}, data) {
      let clonedData = Object.assign({}, data);
      let keyId = data['.key'];
      let ref = getters[`$${data['.ref']}`];
      if (clonedData['.key']) {
        delete clonedData['.key'];
      }
      delete clonedData['.ref'];


      if(keyId) {
        clonedData['test'] = 'tester';
        clonedData['updated'] = firebase.database.ServerValue.TIMESTAMP;
        ref.child(keyId).update(clonedData)
      } else {
        clonedData['created'] = firebase.database.ServerValue.TIMESTAMP;
        ref.push(clonedData)
      }
    },
    VuexFireRemove({getters}, data) {
      let ref = getters[`$${data['.ref']}`]

      ref.child(data['.key']).remove();
    },

  };
}


export function VuexFireEvents(modules) {
  let keys = Object.keys(modules);
  return store => {
    keys.forEach(key => {
      if (!store.getters[`$${key}`] && !store.getters[key]) return;
      runFirebaseEvents(key, store);
    })
  }
}

in a module users module

import {VuexFireSync} from '../plugin'

const state = {

};

const mutations = {

};

const getters = {

};

const actions = {

};

const users = {
  state,
  mutations,
  getters,
  actions,
  ...VuexFireSync('users')
};

export default users;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.