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

I'm curious about the purpose of the "^=" operator in this algorithm for finding the unpaired numbers. What exactly does it do?

I came across a fascinating code snippet that helps find a unique number in a list of duplicate numbers (where each number appears twice, except for one). function findNonPaired(listOfNumbers) { let nonPairedNumber = 0 listOfNumbers.forEach((n) => ...

Implementing shallow routing with the Next.js 13 framework while having appDir functionality activated

Previously in Next 13 (or with appDir disabled), you could achieve the following: const MyComponent = () => { const router = useRouter(); const toggleStatic = () => { if (router.query.static) { router.push(router.pathname, router.pa ...

Issue with Vue.js when attempting to access router property: "Cannot read properties of undefined (reading 'router')" error

I recently started using Vue.js and I've built a simple form for users to input data, which is then stored using an API. Upon submission, I trigger the following function: setup(props, { emit }) { const blankData = { customer: '', ...

Ways to examine the origin of an image based on the attributes of a React component that I have passed as a prop?

I'm facing an issue where I can't use the component's prop to set the src of an image that I imported from a file path in my component's JavaScript file. I have tried different syntaxes but none seem to be working. Here are the formats ...

Collections of ajax triumphs

$(".btn_tab").click(function() { var ids = new Array(); $i=0; $(this).ajaxSuccess(function(e) { alert($i); $( ".tab-content .active table tbody tr td a.elusive-align-justify" ).each(function() { ...

What is the best way to access data from this $scope in AngularJS?

Upon printing selecteditems to the console, this is the output: [{"model":"Lumia","brand":"Nokia","subModel":["Lumia 735 TS","Lumia 510"],"city":"Bangalore"}] I have stored it in $scope.details as follows: var selecteditems = $location.search().items ...

How can I fix the issue of clearInterval not functioning properly in an Electron JS application?

The clearInterval function is not working properly in this code. What can be done to fix this issue? var inter; ipcMain.on("start-stop",(err,data)=>{ console.log(data.data) function start(){ inter = setInterval(fu ...

The error message "Cannot construct apickli.Apickli" is indicating a Type Error

Encountering this issue : TypeError: apickli.Apickli is not a constructor every time I attempt to execute Sendpostrequest.js again in the following step of a scenario. In A.js, the initial call to Sendpostrequest works without any problems. However, ...

Cross-origin resource sharing problem arises when JavaScript is loaded asynchronously using script tags created dynamically

By dynamically creating a script as shown below, the JavaScript source is downloaded asynchronously. let newScript = document.createElement('script'); newScript.src = srcUrl; let firstScript = document.getElementsByTagName('script')[0] ...

Designing a user interface that consists of numerous distinct components

Challenge I'm faced with a dilemma regarding site A, which is built using React. Specifically, I need to find a way to integrate smaller React components into site A whenever a user navigates to a specific page within the site. Each of these smalle ...

Is there a way to incorporate CSS into an element utilizing jQuery when only a class is available for identification, and when the time in the innerHTML is within a 5-minute range from the current time?

I have some HTML code that I need help with: <td class="mw-enhanced-rc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;18:10&nbsp;</td> My goal is to use JavaScript to make the time bold. $('td[class^="mw-enhanced-rc"]').eac ...

Adding complex JSON format to an HTML table involves formatting the data correctly and then using

Utilizing AJAX, I fetched a JSON response and am now looking to map the JSON data into an HTML table structured like this: { "records": [{ "type_id": 000001, "type_desc": "AAAAAA", "type_createby": "Adam" }, { "type ...

When the 'Show More' button is clicked, one Div will smoothly slide over another Div

I've been struggling for hours to find a way to make one DIV slide over another DIV below it instead of pushing it down. The setup is quite straightforward. I have a script that reveals more text when the 'Show More' button is clicked. Desp ...

Displaying a component following data retrieval in Vue.js

I am currently working on consuming an API using axios. Here is the code I have so far: <select> <option v-for="value in values"> value.name </option> </select> // js data(){ values: [], }, create ...

Utilize Angular service to deliver on a promise

Currently, I have a service that is responsible for updating a value on the database. My goal is to update the view scope based on the result of this operation (whether it was successful or not). However, due to the asynchronous nature of the HTTP request ...

Is there a way to incorporate a CSS file into this without explicitly mentioning the color?

I have successfully implemented a PHP solution for changing themes with a cookie that remembers the selected theme color when the user leaves the site. However, I now need to switch this functionality to JavaScript while still utilizing the CSS file. How c ...

What is the reason for a type narrowing check on a class property failing when it is assigned to an aliased variable?

Is there a way to restrict the type of property of a class in an aliased conditional expression? Short: I am trying to perform a type narrowing check within a class method, like this._end === null && this._head === null, but I need to assign the r ...

Trying out the fetch api with Jest in a React Component: A step-by-step guide

As a newcomer to test driven development, I stumbled upon a section that talked about testing/mocking a fetch API. However, I am facing issues while trying to write my own test. In order to practice this concept, I created a simple weather app where I atte ...

What is the process for sending an HTTP request within the Dialogflow -> Fulfillment environment?

When it comes to interacting with the API of my website to rectify the response for Google Assistant, I am facing some difficulties. 'use strict'; var requestNode = require('request'); const functions = require('firebase-function ...

using flexbox in react does not automatically resize

I am attempting to create a layout where the screen is split into two sections - one green block taking up 1/4 of the screen and one yellow block taking up 3/4 of the screen using react.js. However, when I tried implementing the code below, both blocks end ...