[Vuejs]-How to reference a VueUse useFirestore ref in another useFirestore?

0πŸ‘

βœ…

As commented by @EstusFlask, the docs show that it needs to be wrapped in a computed ref.

This is because computed gets recalculated when any of it’s ref values change.

Therefore websiteDocRef becomes this:

const websiteDocRef = computed(() =>
  doc(db, `websites/${user.value?.currentWebsiteId}`)
);

Here is the full code:

<template>
  <div>{{ user }}</div> 
  <div>{{ website }}</div>
</template>

<script setup lang="ts">
import { useAuth } from '@vueuse/firebase/useAuth';
import { useFirestore } from '@vueuse/firebase/useFirestore';
import { doc } from 'firebase/firestore';
import { auth, db } from 'src/config/firebase';
import { User, Website } from 'src/types';

const { user: authUser } = useAuth(auth);

const userDocRef = doc(db, `users/${authUser.value?.uid}`);
const user = useFirestore<User>(userDocRef);

const websiteDocRef = computed(() =>
  doc(db, `websites/${user.value?.currentWebsiteId}`)
);
const website = useFirestore<Website>(websiteDocRef);
</script>

-1πŸ‘

As commented by @Estus Flask, website = useFirestore – this is a mistake, never reassign refs, only their values. Composables are supposed to be used directly in setup, by calling it multiple times you most likely misuse it. Wrap doc() that depends on currentWebsiteId with a computed. It’s already explained in docs, vueuse.org/firebase/usefirestore/#usage

Leave a comment