How can I bind a ref to a Pinia state variable through an action, in Vue 3?

1.1k Views Asked by At

I'm using the useFirestore composable from the vueUse library - I had success in reactively binding my "titles" document to the titles store variable, however when I try to bind userData through an action nothing happens (note: my Firebase config is fine).

What's the correct way to do this?

// user.store.js
import { defineStore } from "pinia";
import { useFirestore } from "@vueuse/firebase/useFirestore";
import { db, doc } from "../../../config/firebase";

export const useUserStore = defineStore("user", {
  state: () => ({
    titles: useFirestore(doc(db, "titles", "available")), // <-- this works and binds the firestore document
    userData: null,
  }),
  getters: {
    getUserData: (state) => state.userData,
  },
  actions: {
    setUserData(uid) {
      this.userData = useFirestore(doc(db, "users", uid)); // <-- this doesn't do anything and userData is `null` in the dev tools.
    },
  }
});

// Component.vue
...
setUserData("my-id");
1

There are 1 best solutions below

0
On

Ah, I neglected to use $patch. This worked for me:

setUserData(uid) {  
  const user = useFirestore(doc(db, "users", uid));
  this.$patch({ userData: user });
}

If I'm using this in the wrong way, please let me know.