Struggling to fetch the last and first name from a document in Firestore using VueJs

https://i.sstatic.net/IdZGi.pngWhen trying to retrieve the last name and first name from a document stored upon signup with a field displayName, I encountered an issue. Despite having a common key as displayName, which should allow me to fetch this information by making a request to firestore using the currentUser object returned after logging in, I am unable to access the lastName from the Firebase documents. I would appreciate any assistance in resolving this matter.

<template>
  <p>Process Payroll</p>
  <h1>{{ user.displayName }} </h1>
  <h1>{{ docs }} </h1>
</template>

<script>
import getUser from '@/composables/getUser'
import { ref, onMounted, watch } from 'vue'
import { projectFirestore, projectAuth } from '@/firebase/config'
import { useRouter, useRoute } from 'vue-router'

export default {
    setup() {
    const { user } = getUser();

    watch(()=> user, () => returnUser())

    const lastName = ref("");
    const firstName = ref("");
    const docs = ref([]);

    const returnUser = async () => {
      const res = await projectFirestore
        .collection("users")
        .where("displayName", "==", "Abe")
        .get();
      if (!error.value) {
        // check your response here.
        console.log(res);
        const doc = res.filter((userObj) => {
          if ("Abe" === userObj.data().displayName) {
            return userObj.data().lastName;
          }
        });
        docs.value = doc;
      }
    };

    onMounted(returnUser)

    return { user, docs, returnUser};
  },
}
</script>

The issue is that only a blank array is being returned instead of the lastName value. Also, there don't seem to be any requests made by Firebase to retrieve the necessary information. In my console, I'm getting a reference error stating "error is undefined" along with "cannot read property displayName of null," despite ensuring through a watch that the user object is loaded. Any guidance on significant code changes to help resolve these errors and display the lastName from Firebase would be greatly appreciated. Please assist as I am new to Vuejs.

https://i.sstatic.net/YjbIP.png

import { ref } from 'vue'
import { projectAuth } from '../firebase/config'

// refs
const user = ref(projectAuth.currentUser)

// auth changes
projectAuth.onAuthStateChanged(_user => {
  console.log('User state change. Current user is:', _user)
  user.value = _user
});

const getUser = () => {
  return { user } 
}

export default getUser

https://i.sstatic.net/C64Og.png

https://i.sstatic.net/DyZnL.png

Answer №1

If you are looking to record all possible combinations of first names and last names, consider implementing the following:

const fetchUser = async () => {
  const response = await database
    .collection("users")
    .where("name", "==", "John") // Ensure it is case sensitive
    .get();

  const combinedNamesList = response.docs.map(doc => `John ${doc.data().lastName}`)
  console.log(combinedNamesList)
  records.value = combinedNamesList;
}

To ensure that displayName is always present in the getUser function, modify it as shown below:

const getUserData = () => {
  // Assign a default value if user is not defined
  return user ? { user } : { displayName: "UnknownUser" } 
}

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

Typescript's forEach method allows for iterating through each element in

I am currently handling graphql data that is structured like this: "userRelations": [ { "relatedUser": { "id": 4, "firstName": "Jack", "lastName": "Miller" }, "type": "FRIEND" }, { "relatedUser": ...

How to incorporate a JavaScript variable into an ERB tag

Exploring the integration of a JavaScript variable within erb <% %> tags has led me to consider using AJAX (refer to How to pass a javascript variable into a erb code in a js view?). As someone new to JavaScript and AJAX, it would be extremely helpfu ...

A guide on organizing and categorizing data by name with angularjs

Presented here is a list of descriptions associated with specific names. I am seeking guidance on how to group or list the descriptions by name. html: <body ng-app="app" ng-controller="MainCtrl"> <div ng-repeat="nameGroup in loopData"> & ...

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

Vue allows a child component to share a method with its parent component

Which approach do you believe is more effective among the options below? [ 1 ] Opting to utilize $emit for exposing methods from child components to parent components $emit('updateAPI', exposeAPI({ childMethod: this.childMethod })) OR [ 2 ] ...

Get the docx file generated with Flask and VueJS

I've been grappling with the challenge of downloading a docx file in VueJS. Initially, I attempted to generate the file on the frontend, but it kept getting corrupted. To solve this issue, I resorted to using Flask to create the docx file, which worke ...

Error encountered when trying to set up Firebase analytics in NextJS: "Missing configuration value for App."

Currently, I am working on a project using Next JS 13 with the default pages directory and incorporating a database. Everything was running smoothly until I decided to integrate Firebase analytics. Initially, it threw an error stating that "window is unde ...

Tips for sorting an array based on various criteria from a separate array

Seeking assistance with filtering results from the data array using two arrays. var data = [{"role":"Frontend", "languages": ["HTML", "CSS", "JavaScript"]},{"role":"Fullstack", ...

Eliminate Tracking Parameters from URL

I rely on UTM parameters to monitor incoming links within Google Analytics. Consider a scenario where my URL appears as follows https://www.example.com/store?utm_source=newsletter&utm_medium=email&utm_campaign=spring_sale I am looking to streaml ...

Issue with React hook state persistence in recursive function

I implemented a recursion custom hook that utilizes a setTimeout function to provide 3 chances for an operation. Once the chances run out, the recursion should stop. However, I encountered an issue where the setTimeout function is not properly decrementin ...

What is the method for creating a loop in Angular?

let m = 5; for (let i = 0; i < m; i++) { document.write(i); } What is the output of i in Angular? This code is not functioning as expected. $scope.B = []; angular.forEach([0, 1, 2, 3], function (value, index) { $scope.B.push ...

Jest remains verdant even in cases where Expected does not match Received

it('User is already present as a supplier', (done) => { const store = mockStore({}, [{ type: 'get_user', data: { } }]); return store.dispatch(userGetAction({ role: 'supplier' }, () => {})).then(() => { t ...

What is the best way to change an asterisk symbol into 000 within a currency input

In my ASP.NET application, I have a currency text box. I have the following script: <script type="text/javascript> function Comma(Num) { //function to add commas to textboxes Num += ''; Num = Num.replace(',', ...

Issues with the functionality of AngularJS checkboxes

I'm currently working on a basic AngularJS project to improve my skills. Below are the code snippets I've included. I have two sets of JSON data. One set contains a list of grocery items, while the other set includes the items selected by the us ...

When using the Composition API in Vue 3, the "Exclude" TypeScript utility type may result in a prop validation error

Currently, I am utilizing Vue 3 alongside the Composition API and TypeScript, all updated to their latest stable versions. If we take a look at the types below: export interface Person { name: string; } export type Status = Person | 'UNLOADED&ap ...

Intercepting HTTP responses to handle headers

I'm facing an issue where I am trying to retrieve a custom header sent from the server in my $http response interceptor. However, the only header that is accessible is the Content-type header. How can I troubleshoot this problem? Here is part of my $ ...

Managing post requests in node.js using busboy and then multer

I'm currently facing an issue with busboy (or multiparty) and multer while trying to parse my request. Initially, the request is received successfully using busboy, where I proceed to create a folder and update my database. However, when I attempt to ...

`Connected circles forming a series in d3`

I am currently working on developing an application where the circles are positioned such that they touch each other's edges. One of the challenges I am facing is with the calculation for the cx function. .attr("cx", function(d, i) { return (i * 5 ...

Struggling to make button switch in my Spring Boot Application (e.g. from "Add to Cart" to "Remove")

My application allows users to add items to their cart, which are then persisted using Spring Data JPA and saved in a MySQL database. I am looking to change the text from "Add to Cart" to "Remove" when the button is clicked, and vice versa. I have attempt ...

MongoDB table collections (table names in other databases)

After setting up my express server to connect to mongodb, I encountered an issue despite everything working fine initially. I created a collection in my mongodb called projects (plural form). In my project.model.js file, I defined the model as follows: c ...