Firebase, fetching user-specific documents in a web application

I've been experimenting with Firebase in my web project and I'm curious about the best way to retrieve data from Firestore specific to the currently logged-in user.

This is what I attempted:

import firebase from 'firebase';

const uid = firebase.auth().currentUser.uid;
firebase.firestore().collection('posts').add({
        title: this.title,
        content: this.content,
        user: uid
})
firebase.firestore().collection('posts').where("user", "==", uid).get()
    .then(snapshots => {
      this.posts = snapshots.docs.map(doc => {
        const data = doc.data();
        return {
          id: doc.id,
          title: data.title,
          content: data.content
        }
      })
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error.message);
    });

While this method works, it feels a bit amateurish. I'm wondering if there's a more professional approach for achieving this task.

Answer №1

implement the isEqualTo method in the following way:

where("user", isEqualTo: uid).get()

Answer №2

In my opinion, your code appears to be well-written and easy to understand - there's no need to strive for a 'professional' look if it means adding unnecessary complexity. Below is just one individual's perspective on incorporating variables more effectively :)

const database = firebase         
    .initializeApp({ 
        // configuration details...
    }) 
    .firestore();

const authentication = firebase.auth();
const currentUserID = auth.currentUser.uid;

const postReference = database.collection('posts');

//  add 
const { title, content } = this;
postReference
    .add({
        title,
        content,
        user: currentUserID
    })

//  get 
postReference
    .where('user', '==', currentUserID)
    .get()
    .then(snapshot => {
        this.posts = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))  
    })
    .catch(console.error)

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

Getting data for Selectize.js

I've implemented Selectize.js to create a tagging feature for assigning users to jobs, utilizing the existing users within the system. In my scenario Following the provided documentation, I have included a select box with the multiple attribute that ...

Retrieve information from a changing HTML table

I am working on a nodejs express project that features a Dynamic Table within my application. Users can add or remove rows and enter values into cells, but I am struggling to extract these values from the table without using jquery. My goal is to then inse ...

What's the process for creating a synchronous function in AngularJS?

Is there a way to make storyboard.getAdressTimeLine run synchronously? I need storyboard.drawTimeLine to continue executing only after storyboard.getAdressTimeLine is done for (var i = 0; i < response.data.length; i++) { var obj=response.data[i]; var d ...

Say goodbye to the 'Access-Control-Allow-Origin' issue when using HMVC Codeigniter!

Upon loading the page, I encountered an error in my console that stated: A font from origin 'http://example.com' was blocked from loading due to Cross-Origin Resource Sharing policy. The requested resource does not have an 'Access-Contr ...

chart.js version 3 does not display the correct date data on the time axis

Struggling to make chart.js work with a time axis is proving to be quite challenging for me. The code I have is as follows: <html> <head> <script src="https://cdn.jsdelivr.net/npm/moment"></script> <script src="https://cdnjs.clo ...

Ensure a consistent number of draggable elements in HTML/JavaScript

Below is the HTML/JS code snippet: <!DOCTYPE HTML> <html> <head> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.targ ...

How can I locate the element immediately preceding $(this)?

Struggling to retrieve the value of the $(.subname) when the .bigadminbutton is clicked and calling the updateSub() function. I have tried various methods like prev, sibling, parent, children, find, but none seem to work. This minor task is taking up too ...

Typography splits into a second line within the grid on the toolbar

I need help with my Appbar design. I want to align the title (Lorem ipsum text) on the left and the buttons on the right. However, when I tried implementing the code below, I noticed that there seems to be a maximum width causing the text to break into t ...

In Javascript, assign default values to an array and update them with new values upon the click of a

My goal is to create a quiz that populates an array. Initially, the quiz is empty but I aim to assign it a default value. This serves as my question navigation: /** * * @param {int} question * @returns {QuizPart} ...

Tips for maintaining a user's logged-in status when the "remember me" option is selected

I need to implement a feature that keeps a user logged in even if they refresh or close the browser. This is the code I have written: index.php <?php include_once('elogFiles/view/myIncludes.php'); ?> <div class="container" ...

Transform a JavaScript object array into a collection of individual values

Given a list of objects structured like this, I am looking to transform it into a list of values based on their corresponding IDs. Original = [ {id: 1, value: 12.2494, time: "00:00:00.14"}, {id: 1, value: 4.5141, time: "00:00:01.138"}, {id: 1, ...

What could be causing my Firebase callbacks to activate more than once?

My current setup involves a small node server that's keeping an eye on firebase for any changes and triggering email notifications based on specific conditions. Check out the code snippet below: var Firebase = require('firebase'); var ref ...

Grab the URL from React Router

I need assistance with writing a function that updates the current location to match the route of a clicked button. Currently, the code is returning the URL of the page where the button was clicked, not the path related to the button itself. Are there an ...

Launching a React project using the terminal - my step-by-step process

I'm attempting to initiate a new react-app utilizing the command npx create-react-app <app name> as shown below: npx create-react-app new-app However, after downloading, it seems to be stuck. It's not progressing at all. I've even rei ...

Trouble arises with AJAX due to DOM traversal errors

I am trying to set up a system for liking and disliking with a counter. However, I am facing issues with my AJAX call, specifically when attempting to change the HTML of selected elements in the view after sending values to the DB. The element in question ...

Undefined variable when initializing with ng-init

As a newcomer to AngularJS (and JavaScript in general), I'm currently facing an issue that I could use some help with. Below is the HTML template I am using: <ion-view view-title="Playlists"> <ion-content> <ion-list> ...

What is the process for submitting a form on consecutive URLs?

I have a form that requires input for settings and includes two buttons: one to save the form and another to both save and execute the settings. <form method="post" action="/settings/{{id}}/save"> <!-- input fields --> ...

Retrieving file icons from a directory using Node.js fs

I am interested in creating a file system explorer application that displays files with icons. I am using node-webkit and the files can be executables, directories, or regular files. In the file list, I want to show the file's icon and name. Is it po ...

Tips for utilizing an npm package in conjunction with Hugo

I created a basic hugo site with the following command: hugo new site quickstart Within the layouts/_default/baseof.html file, I have included a JavaScript file named script.js. Inside script.js, the code looks like this: import $ from 'jquery' ...

ng-repeat to prevent duplicate items from displaying

I intentionally have duplicates in my array of items and I am looking for a way to hide just one of them when clicked within my ng-repeat. Is there a way to hide only one of the duplicated items on click? I feel like I might be overlooking something, as ...