How can you use the `useCollection()` method in VueFire to create a reactive collection before specifying the collection path?

I am currently in the process of learning about Vue and Vuefire. My main objective is to retrieve a collection of documents (recipes) associated with a user's unique ID, which is stored as a subcollection within the user document.

The firestore path leading to this collection typically looks something like users/${user.uid}/recipes. The issue arises when I attempt to declare my collection using

recipesStore = useCollection(...)
initially, as there is no defined path at that stage. Upon page refresh, an error usually appears in the console:

My assumption is that this error occurs when the path/userID has not yet been determined.

In my code, the user ID is obtained only after the user signs up. I approach defining reactive collections by starting with an empty object and later updating it upon sign-in with the correct path pointing to the user's collection, utilizing the function updateCollectionWithUser(user).

export const recipesCollection = ref({})
export const recipesStore = useCollection(recipesCollection, {wait: true})

export const updateCollectionWithUser = async (user) => {

    recipesCollection.value = collection(db, `users/${user.uid}/recipes`)

}

Although this error does not seem to impede functionality, I suspect it may indicate a larger issue within my code structure. Typically, I do not encounter this error in the console upon signing in, but it becomes visible upon refreshing the page, despite successfully loading the collection.

Could this issue be related to Vuefire's inability to work with an empty path, or perhaps tied to Promise handling (which remains somewhat obscure to me)? What would be the best approach to tackle an unknown path to a collection?

Answer №1

Utilize a reactive approach when working with the user data in order to stay updated with any changes in state.

To integrate VueFireAuth into your VueFire plugin, follow these steps:

// In your main.js file
import { VueFire, VueFireAuth } from 'vuefire'
app.use(VueFire, {
  firebaseApp: createFirebaseApp(),
  modules: [
    // ... other modules
    VueFireAuth(),
  ],
})

  // Use the useCurrentUser() composable to retrieve the current user as a reactive variable 
  import { useCurrentUser } from 'vuefire'

  const user = useCurrentUser();

  const recipeRef = computed(() => {
    return getDocs(collection(db, `users/${user.value?.uid}/recipes`));    
  })

  // Keep userRecipes synchronized with the data source
  const userRecipes = useCollection(recipeRef); 

For more detailed information, check out VueFire's documentation at

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting the width of a nested Angular custom directive within an *ngIf statement to an absolute value

I'm struggling with a custom angular directive that I only want to display conditionally using ng-if. The directive contains HTML elements, one of which is positioned absolutely. My goal is to make the absolute element's width match the root wid ...

Angular 7: Resetting multiple dynamically generated checkboxes back to their original state with the click of a button

I have created a child component that contains 3 checkboxes, generated dynamically using ngFor, along with Apply and Cancel buttons. In the parent template, I include the selector tag for the child component. The parent component accesses this child compo ...

The issue of drop shadows causing links to not work properly in Internet Explorer

I am currently working on a website design that features a fixed menu positioned behind the body. When the menu icon is clicked, some jQuery code shifts the body to the left. To create the effect of the fixed menu being positioned underneath, I have added ...

modifying a record in MongoDB with the help of Mongoose

I need help with updating a collection in MongoDB using Mongoose. function check (db) { var hours = 60 * 60 * 1000 var threeHours = 3 * hours; var lastUpdated = null; db.collection("profile").find({userName: "Rick"}).toArray(function(er ...

Why does my jQuery map code work in version 2.0 but not in version 3.0?

I've encountered an error with a jQuery map snippet that I'm trying to troubleshoot. It was working fine under jQuery 2, but after upgrading to version 3, it doesn't work anymore and I can't figure out why. Feeling stuck! var menuIte ...

How to Make Page Slide in Either Direction Based on User Click Location

Although the title of my question may not be very descriptive, I am essentially trying to implement a functionality where a page will slide right if a user clicks a link to the right of their current active link, and slide left if they click a link to the ...

Receiving an undefined value of x in AJAX and web API

In the Javascript code, I am attempting to display the listview of reviews when a user clicks on a movie. However, I am encountering errors in the console for the second and third movies - Batman and Avatar - stating that they are not defined. Additionally ...

Why are the height and width values I specified not matching the values returned?

I am currently learning HTML and JavaScript, specifically diving into the width() and height() methods in JavaScript. Setting the dimensions of div1 to 100px for height and 300px for width, I encountered a discrepancy when running the code. Upon execution ...

Having issues with ng-src and images not loading in the application

Is there a way to dynamically change the image source using ng-src? I've been attempting to switch the image file source based on an onclick event using the code below, but it's not working as expected. <html ng-app="ui.bootstrap.demo"> ...

Unable to show the name of the chosen file

After customizing the input [type = file], I successfully transformed it into a button with a vibrant green background. Here is the code snippet that enabled this transformation: <style> #file { height:0px; opacity:0; } ...

Issue: The variable does not appear to be getting updated

After spending the last 2 hours analyzing this JS code, I am still unable to figure out why the variable "message" is not being changed to "User already exists." The bizarre thing is that the code block labeled "Inside first if" is executed, but the "mes ...

Encountering an issue in Android Studio 1.3.1 when trying to create a SQLite

I encountered an error on line 26 of MainActivity.java. A Java NULLPOINTER Exception is being displayed. Can someone please advise me on how to resolve this issue? My code is available on GitHub. https://github.com/happyshravan/SQLite Latest LogCat error: ...

The presence of an additional bracket is being triggered by the JSON array following

Currently, I am developing a function in Freemarker to iterate through all selected checkboxes and then display the same response on the form itself. The form is structured in Freemarker format, and I am utilizing JavaScript to create separate arrays for e ...

Trigger the fire event on .click() except when text is being selected

I am currently working on a chat box project and I want the input field within the message area to automatically get focused when the user clicks anywhere in the chat box. However, I don't want this functionality to interfere with text selection for c ...

Using a Key to Activate the Trigger Button Instead of a Mouse Click

I am seeking assistance with a specific issue. I currently have a timer with a stop button that can be clicked with a mouse, but I want to enable the button to also be activated via a key press. I have attempted different methods such as using document.add ...

The browser automatically adds a backslash escape character to a JavaScript object

When attempting to send an MQTT message to a topic from my angular app, the message needs to be in a specific syntax: { "Message": "hello" //the space after : is mandatory } However, upon sending the message in the correct format, the browser aut ...

Activate the mouseenter event as soon as an animated element makes contact with the cursor

As I venture into the world of web development, I am currently working on creating a game where the main objective is to avoid touching moving circles with the cursor. My approach involved using a mouseenter event as shown in the JSFiddle example below: $ ...

What steps can I take to ensure my Vue website is tested on various devices and views before it goes live online?

My current project involves developing a website that utilizes Vue-js for the front-end, and Node + MySQL for the back-end. During development mode, when I connect to the internet and run npm run serve, I come across these lines in my command-line: https: ...

Executing successive setState() calls within a React method: Achieving "synchronous" behavior

During a recent issue in my React application, I encountered a scenario where I needed to make multiple setState() calls within one method and ensure that certain code executed AFTER the states were set. The following code snippet showcases a Dialog box ut ...

Discover the best method for sorting an array into a new array using Angular

const arr1 = [ { id: "c1", section: { name: "emerald", room: { id: "r1", name: "Room 1" } } }, { id: "c2", section: { name: "diamond", room: { id: ...