What is the best way to retrieve individual records from a Database?

I have a page that displays all the profiles from my database. What I want to achieve is, when someone clicks on an individual profile, they should be directed to a profile page showing the rest of the data corresponding to the id clicked. However, I am facing issues in making it work. Below is the JavaScript file to fetch individual profiles.

import { projectFirestore } from "../Firebase/Config";
import { ref } from "vue"

const getPBasic = (id) => {
    const PBasic = ref(null)
    const error = ref(null)

    const load = async () => {
        try{
            let res = await projectFirestore.collection('Basic').doc(id).get()

            PBasic.value = {...res.data(), id: res.id}
               console.log(PBasic.value)
            
        }
        catch (err){
            error.value = err.message
            console.log(error.value)
        }
    }

    return { PBasic, error, load}
}

export default getPBasic

Here's the Vue page where I want the data to be displayed after clicking on a profile from the previous page.

<script>
import getPBasic from "../Composables/getPBasic";
const {PBasic, error, load} = getPBasic(route.params.id);
load();

export default {
  name: "Slider",
  data() {
    return {
     images: [
        "/src/assets/sample-1.jpg",
        "/src/assets/sample-2.jpg",
       "/src/assets/sample-3.jpg",
        "/src/assets/sample-4.jpg"
      ],
      
      currentIndex: 0
    };
  },


  methods: {
 

    next: function() {
      this.currentIndex += 1;
    },
    prev: function() {
      this.currentIndex -= 1;
    }
  },

  computed: {
    currentImg: function() {
      return this.images[Math.abs(this.currentIndex) % this.images.length];
    }
  }
};

</script>
<template>
<div v-if="error">{{ error }}</div>
<div v-if="PBasic" class="PBasic">
<br><br>
<p>{{ PBasic.Name }} </p>
<p>{{ PBaic.Age }} </p>
</div>
 <div v-else>
  <spinner/>
 </div>

This is just a snippet of what I have done so far. If anyone has any ideas or suggestions, I would truly appreciate it. Thank you.

Answer №1

To retrieve the necessary data, consider executing your getPBasic function during page load.

An effective approach would be to run the getPBasic function within a lifecycle hook that triggers on page rendering, such as the mounted() hook or onMounted() in vue3 script setup.

Since your getPBasic function operates synchronously, ensure to utilize await for proper retrieval of the return value.

A potential code implementation could resemble the following:

<script>
import getPBasic from "../Composables/getPBasic";
const {PBasic, error, load} = getPBasic(route.params.id);

export default {
  name: "Slider",

  mounted(){
    let {PBasic,error,load} = await getPBasic();
    this.PBasic = PBasic;
    this.error = error;
    this.load = load;
  },

  data() {
    return {
     PBasic:{},
     error: null,
     load: false,
     images: [
        "/src/assets/sample-1.jpg",
        "/src/assets/sample-2.jpg",
       "/src/assets/sample-3.jpg",
        "/src/assets/sample-4.jpg"
      ],
      
      currentIndex: 0
    };
  },


  methods: {
 

    next: function() {
      this.currentIndex += 1;
    },
    prev: function() {
      this.currentIndex -= 1;
    }
  },

  computed: {
    currentImg: function() {
      return this.images[Math.abs(this.currentIndex) % this.images.length];
    }
  }
};

</script>
<template>
<div v-if="error">{{ error }}</div>
<div v-if="PBasic" class="PBasic">
<br><br>
<p>{{ PBasic.Name }} </p>
<p>{{ PBaic.Age }} </p>
</div>
 <div v-else>
  <spinner/>
 </div>

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

Please be cautious not to directly change the state. Remember to always use setState() in ReactJS to update

Looking for a way to update states in React.js using the "=" sign instead of the setState method? Check out the code below for an example where I'm trying to update the state of an object within another object. However, I'm encountering an error ...

Requirements for adding information to a database table

I'm new to JavaScript and facing an issue that I need help with. I am trying to insert data into a database table based on certain conditions in my code, but even though I receive an error message when I input incorrect values, the data still gets ins ...

Looping through a JSON object to create a table showcasing public holidays

Currently, I am working on creating a table that lists all the public holidays. The table comprises rows with holiday names on the left and dates on the right. Unfortunately, the table only displays data from the final array of the JSON object, whereas I ...

Does each imported module in a Next.js app run multiple times?

There is a common understanding that when a module is imported multiple times within a JavaScript program, it only executes once during the first import. Informative article: The concept is straightforward: each module is evaluated just once, meaning th ...

Individual Ajax data

Starting out with javascript, I'm a bit unsure of how to tackle this task. Essentially, I am looking to implement a for loop within the ajax data call, rather than listing each item manually. jQuery(document).ready(function() { ...

At times, Sakuli Test may encounter a 503 error, indicating that the service is temporarily unavailable

Test result shows OK status, but an error message is displaying on the screen. Can anyone provide assistance in identifying what needs to be checked? Error: Error in testcase Form-test An error occurred while trying to locate the element "Jetzt anforder ...

Suggestions for placing a script under the scripts menu in Illustrator CS5.1

My script for Adobe Illustrator CS5.1 is not showing up in the scripts menu despite trying to place it in various directories such as: C:\Program Files\Adobe\Adobe Illustrator CS5.1\Presets\en_GB\Scripts\ C:\Progra ...

The completion event was not triggered during the AJAX request

I am having an issue with a function that I have created to make an ajax call. Despite using the .done method, it does not seem to be firing as expected. Upon checking my console for errors, I came across the following message: https://i.sstatic.net/CbYBR ...

What causes the "Invalid hook call" error to occur when the useQuery function is invoked?

Encountering an issue while trying to use the useQuery() function from react-admin within a custom component. Despite the clear error message, I'm struggling to determine the right course of action. Visiting the provided website and following the inst ...

Angular not firing slide.bs.carousel or slid.bs.carousel event for Bootstrap carousel

I've searched high and low with no success. I'm attempting to detect when the carousel transitions to a new slide, whether it's automatically or by user click. Despite my numerous attempts, I have been unable to make this event trigger. I ha ...

What are the steps to utilizing dynamic data from a file in JavaScript?

I've got a Python script constantly generating data, and I'm looking to use that data to make some changes to an object in JavaScript. Is there a method to accomplish this? ...

Set up local npm packages for easy access by different projects

Can someone explain to me how npm works compared to Maven (I have a background in Java) when it comes to package management? I've developed a generic component using Angular 4 that will be used across multiple projects. I've published it to our n ...

Is there a way to utilize enums containing dashes in GraphQl JS?

Unfortunately, GraphQL enums do not support the use of dashes and only accept underscores. In my current situation, I have enums that include dashes. These enums are already established and changing them would likely cause issues in areas that are difficu ...

Is there a way to convert a method for computed properties into GETTER and SETTER functions?

I am just starting to learn about Vuex and decorators. I am currently working on a search bar that filters characters based on user input. <input class="form-control" type="text" v-model="searchPhrase" placeholder ...

${resource} and ${promise} are both returning undefined values

Encountering the following error: TypeError: Cannot call method 'then' of undefined while working with the code below: App.controller('MainCtrl', ['$scope', 'Main', 'MainFilter', function($scope, Main, M ...

Is polymer routing the best choice for large-scale websites?

I am currently working on a large project that consists of various layouts and structures, totaling around 100 different pages. Despite the variations in content, the core elements such as headers and menus remain consistent throughout. To streamline my ...

Modify the css with JQUERY when there are no rows inside the tbody section

Is it possible to change the css using jquery if there are no rows in the table body? I have attempted this but my current approach is not working. I tried adding an alert within the if statement, but the alert did not appear. My goal is to hide the table ...

I'm looking for a way to check and validate three input fields for date, month, and year individually using either jQuery or JavaScript. Can anyone

My form requires input fields for date, month, and year separately. The validation rules are as follows: Date should be between 1-31 and month should be between 1-12. The desired date format is dd mm yyyy. Could someone kindly help me with the HTML code ...

What is preventing the Date Picker in Selenium from accepting attribute values when using JavaScript for the Spice Jet application?

My implementation of JavaScript for the Date picker in Selenium is running successfully, however, the date is not being selected in the date picker. public class SpicJetBooking { static WebDriver driver; public static void main(String[] args) t ...

Deciphering a JSON Array in JavaScript to extract specific components

I have a brief snippet for a JSON array and a JavaScript function that currently returns a single argument: <!DOCTYPE html> <html> <body> <h2>JSON Array Test</h2> <p id="outputid"></p> <script> var arrayi ...