Retrieving Firestore information as a JavaScript object

I'm working on retrieving data from Google Firestore as a JavaScript object in Vue.js (3). It functions correctly when used within a V-for loop, but I also need to utilize the array in methods. How can I convert the Firestore data into a basic JavaScript object? I attempted using JSON.parse(), however, it did not yield results.

The retrieved data looks like this:

This code shows how it is implemented:

<template>
  <section>
    <div id="testWrapper">
        <div>
            <p>{{ list }}</p>
        </div>
    </div>
  </section>
</template>

<script>
import { useLoadClients } from "../../firebase.js";


export default {
    data(){
        return{
            list:[]
        }

    },
    async mounted(){
        const newList = await useLoadClients()
        this.list= newList
    }
}
</script>

Below is the Firebase configuration (with the API key censored):

import firebase from "firebase/app";
import "firebase/firestore";
import { ref, onUnmounted } from "vue";

const config = {
  apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  authDomain: "hourly-3295e.firebaseapp.com",
  databaseURL:
    "https://hourly-3295e-default-rtdb.europe-west1.firebasedatabase.app",
  projectId: "hourly-3295e",
  storageBucket: "hourly-3295e.appspot.com",
  messagingSenderId: "434096768140",
  appId: "1:434096768140:web:16bca36e806af1d7e027a9",
  measurementId: "G-XMHZQHM81H",
};

const firebaseApp = firebase.initializeApp(config);

const db = firebaseApp.firestore();
const clientCollection = db.collection("clients");

export const createClient = (client) => {
  return clientCollection.add(client);
};

export const getClient = async (id) => {
  const user = await clientCollection.doc(id).get();
  return user.exists ? user.data() : null;
};

export const updateClient = (id, client) => {
  return clientCollection.doc(id).update(client);
};

export const deleteClient = (id) => {
  return clientCollection.doc(id).delete();
};

export const useLoadClients = () => {
  const clients = ref([]);
  const close = clientCollection.onSnapshot((snapshot) => {
    clients.value = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
  });
  onUnmounted(close);
  return clients;
};

Answer №1

When dealing with Snapshot.data(), keep in mind that it is essentially a Javascript object, even though it may appear as text when printed within a text element. If you find yourself needing to convert it from text to an object, simply utilize JSON.parse(jsonString)

To gain further insight into the type of data returned by Snapshot.data(), I suggest using typeof snapshot.data() which will provide a string indicating whether it is a "string" or an "Object".

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

Troubleshooting issues when integrating three.js GLTFLoader() with TypeScript due to conflicts with zimjs

Successfully loading a model using three.js GLTFLoader() with TypeScript in a nuxt.js application: this.mGLTFLoader = new (<any>THREE).GLTFLoader(); this.mGLTFLoader.load(pPath, (gltf) => this.onLoad(gltf), (xhr) => this.onProgress(xhr), (e) = ...

Ways to conceal the 'Return to Top' button in a script that is only revealed after navigating to the bottom of the page

Can anyone help me hide the 'Back to Top' button in a script that only appears after scrolling to the bottom of the page? I need to take screenshots without it showing up. I've tried using the code below, but the 'Back to Top' but ...

I am experiencing issues with the search feature in angular and node.js that is not functioning properly

Need assistance with debugging this code. I am currently working on adding search functionality to my Angular web page. However, when testing the code in Postman, I keep receiving the message "NO USER FOUND WITH USERNAME: undefined". Additionally, on the w ...

Automatically change a text based on its location

Currently leveraging the amazing flexible-nav to showcase the current subtopic within my post. I am also considering the possibility of extracting this current-string and showcasing it at the top of the page in my main navigation bar. This way, the text w ...

How to link an external CSS file to a Vue.js project

I created a new project using @vue/cli and now I want to add an external CSS file to my App.vue Here's what I attempted: <template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | ...

What causes these queries to function separately but fail when combined?

I am facing an issue with combining 2 queries in my Firestore collection. These are the 2 examples that work: database .collection('servicebonnen') .where('medewerker', '==', 'CEES') and: database .collecti ...

Leverage the power of AJAX for searching in Laravel 5.3

This section contains views code related to form submission: {!! Form::open(['method'=>'GET','url'=>'blog','class'=>'navbar-form navbar-left','role'=>'search']) !! ...

A guide to accessing REST services in AngularJS using basic authentication

I currently have a REST service up and running on my server. Using Chrome Postman, I am able to access this service with Basic Authentication. However, I now want to build a user interface in AngularJS to display the data received from the REST service. T ...

Ways to recover information that is not typically found

My firebase database has two main trees: "tag" and "user". Each user is associated with a set of tags, referred to as preferences. Here is the structure of my database: I am trying to display a list of preferences that a specific user does not have. Exam ...

I encountered an error while attempting to import a file into Firebase Storage

I've been struggling to upload files from Firebase Storage and encountering errors despite reading the documentation and various blogs on the topic. I'm looking for the most effective approach to resolve this issue. import { storage } from ' ...

Having trouble with updating label text in MUIDataTable in ReactJS?

Looking to implement multi-language support in MUI Datatables. I have been able to modify the translations, but when attempting to change languages by providing a different object with new translations (verified using console log), the label texts do not u ...

Retrieving information and employing the state hook

Currently, my goal is to retrieve information from an API and utilize that data as state using the useState hook. fetch('https://blockchain.info/ticker') // Execute the fetch function by providing the API URL .then((resp) => resp.json()) // ...

Vue - unable to display component CSS classes in application when using class-style bindings

Just diving into Vue and starting with class-style binding syntax. I'm facing an issue where the CSS classes for header and footer that I've defined are not displaying, even though I've referenced them in the component tags. Can't seem ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

Accessing elements within a ReactJS map structure using the material-ui Selectable List component is not supported

I'm facing a dilemma. Unfortunately, my proficiency in English writing is not up to par... ※Please bear with me as it might be hard to follow. I'm trying to choose the ListItem component, but for some reason, I can't select the ListIt ...

Close pop-up upon successful AJAX response in ASP.NET MVC

I have a modal in my view that allows me to create a new record in the database. The view for this functionality is contained within a partial view. Below is the code for the view: <script src="~/Scripts/jquery-3.1.1.js"></script> To han ...

What distinguishes running rm -rf node_modules + npm i from using npm ci?

When using a Unix system and needing to clean out the node modules folder, is there any benefit or distinction between executing rm -rf node_modules followed by npm i as opposed to npm ci My understanding is that both yield the same outcome, but is th ...

eliminating and adding a node

Is there a way to replace the existing span elements inside the div (<div id='foo'>) with newly created nodes? I have been looping through all the children of the div, using removeChild to remove each node, and then appending a new node in ...

Using a structural directive in Angular 2 that accepts a String as an input

I am attempting to develop a custom structural directive using the example provided here When trying to pass a string as an input with a slight modification, I encountered an issue where the input value was returning 'undefined' when calling th ...

When the JSON object is transferred to the node server, it undergoes modifications

With the following code snippet, I have managed to develop a function that generates JSON data and transmits it to server.js (my node server). function deleteEmail(i) { emailObj.splice(i, 1); var general = {}; var table = [] general.table ...