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;
};