What is the most effective way to guide each user to their individual data?

I have stored a group of users in Firebase Firestore.

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

Next, I built a Vue component that displays an image with a router-link to the user profile. When clicking on the picture, it should navigate to the user's profile page.

<router-link v-bind:to="{ name: 'view-post', params:{ userId:post.userId}}">
  <v-img :src="post.image" alt="pic"></v-img>
</router-link>

My Vue component code above is quite plain at the moment. It includes a template layout for content display.

   <template>
     <v-layout row wrap>
      <v-content>


      </v-content>
     </v-layout>
   </template>

  <script>
   import { mapState } from 'vuex'
   const fb = require('../firebaseConfig.js')

   export default {
    name: 'view-employee',
    data: () => ({

    }),
    computed: {
     ...mapState(['userProfile', 'currentUser', 'posts'])
    },
    methods: {

    }
  }
 </script>

The computed property ...mapState within the component stores information such as posts, users, and current user fetched from Firestore.

As for Router.js:

import Vue from 'vue'
import Router from 'vue-router'
import firebase from 'firebase'
import World from './views/World.vue'
import Login from '@/components/Login'
import ViewEmployee from '@/components/ViewEmployee'

 Vue.use(Router)

   const router = new Router({
     mode: 'history',
     routes: [
      {
        path: '/login',
        name: 'login',
        component: Login,
        meta: {
          requiresAuth: false
        }
      },
      {
       path: '/world',
       name: 'world',
       component: World,
       meta: {
        requiresAuth: true
       }
      },
      {
       path: '/post/:userId',
       name: 'view-post',
       props: true,
       component: ViewEmployee,
       meta: {
        requiresAuth: true
       }
     }
   ]
 })


  export default router

Answer №1

To implement the functionality in your Vue router, follow these steps:

1/ Within your view-post component (accessed via /post/:userId), retrieve the value of userId using this.$route.params.userId.

2/ Use the value of userId to fetch data from Firestore in the created lifecycle hook.

3/ Display the fetched data on your page.

For a detailed explanation and examples, refer to the Vue router documentation that covers fetching data after or before navigation: https://router.vuejs.org/guide/advanced/data-fetching.html

If you opt for the Fetching After Navigation approach, here's an example code snippet to display the userName:

<template>
  <div>
    <div class="loading" v-if="loading">
      Loading...
    </div>

    <div v-if="error" class="error">
      {{ error }}
    </div>

    <div v-if="userName" class="content">
      <h2>{{ userName }}</h2>
    </div>
  </div>
</template>

export default {
  data () {
    return {
      loading: false,
      userName: null,
      error: null
    }
  },
  created () {
    // Fetch data when the view is created and being observed
    this.fetchData();
  },
  watch: {
    // Re-fetch data if route changes
    '$route': 'fetchData';
  },
  methods: {
    fetchData () {
      var vm = this;
      vm.error = vm.post = null;
      vm.loading = true;

      // Assuming there's a Collection userProfiles
      // with documents having ids same as userIds
      fb.collection("userProfiles").doc(this.$route.params.userId).get()
      .then(function(doc) {
         if (doc.exists) {
           vm.loading = false;
           vm.userName = doc.data().userName;
         } else {
           vm.error = "No such document!";
         }
       })
       .catch(function(error) {
           vm.error = "Error getting document:" + error;
       });

    }
  }
}

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

Execute JavaScript code once the XMLHttpRequest has completed execution

I'm facing an issue where the JavaScript code is executing faster than the XMLHttpRequest. I am hesitant to resolve it using: setTimeout(function() {}, 100); Below is a snippet of my code: function change_country(id) { if (window.XMLHttpReques ...

Executing filepicker.io Javascript API calls may lead to unsafe errors in Javascript

I am currently using AngularJS and encountering an issue when trying to call filePicker.pickAndStore from my Upload controller. Every attempt to use a filepicker.io API function triggers an "Unsafe Javascript attempt" error: The frame requesting access ...

Troubleshooting custom filtering with jQuery Datatables across different tables is presenting challenges

I am currently utilizing the Datatables 1.10 jQuery plug-in and I am interested in implementing the custom search feature to filter two tables simultaneously on a single page, as shown below: function applyFilterByErrorClass(propertiesTable, errorClassNam ...

Interactive JQuery autocomplete feature for the div element

Hey there, I have a question about using jquery textcomplete. It seems like a simple task, but I'm not sure how to accomplish it. I've created a DEMO without jquery as reference. My question is this: How can I make the .textBox div automatical ...

Can we rely on the render method to display the updated state immediately after invoking setState within

Is it guaranteed that the state will exist in the render method if I call setState within componentWillMount without using a callback? According to Facebook, "componentWillMount is called before render(), therefore calling setState() synchronously in this ...

Unable to reset select2 within any function

I am attempting to programmatically add select2. Below is my code snippet: $(document).on("click", "#btnAddRow", function(e) { var newText = $(".rawRow").html(); var lastText = '<div class="row productInfoRow" style="margin-top: 5px;">&apos ...

Using JavaScript's FOR loop in combination with AJAX

I'm encountering an issue with using AJAX and a FOR loop. Within my PHP file, there are several if statements that return different prices based on a number range (1-9). For example: 1 -> echo "15.20"; 2 -> echo "11.10"; 3 -> echo "13.65"; ...

Tiny cutout circle nestled within a larger circle, subtly placed in the bottom right corner using Bootstrap

In my JavaScript code, I have created an array of images arranged in a row on the webpage using the split method. The images are displayed in circles. However, I now need to add a smaller circle cutout at the bottom right of each larger circle to showcase ...

Unable to set up service worker with Workbox window

I need help migrating from v3 to v4 in my Vue.js app. I am using workbox-window (CDN) and workbox-webpack-plugin for this task. While everything works fine locally with an http-server, I encounter an error after deployment that prevents the service worker ...

Merge two JavaScript functions into a single function

Upon inheriting some old code, I embarked on a mission to clean it up. Given that jQuery is being used on the site, utilizing it seemed like the best way to maintain simplicity and cleanliness. function address_finder_callback() { address_finder_sette ...

insert a gap between two elements in the identical line

Is there a way to create spacing between two text fields in the same row? I have tried using margins, paddings, and display flex in the css file but haven't been successful. import "./styles.css"; import TextField from "@material-ui/cor ...

What is the best way to retrieve the values of all the keys in Firebase Realtime Database?

At first, I only retrieved the values associated with each key. However, upon further reflection, I realized that I actually need to obtain the keys themselves and then access the corresponding values. I have now commented out my previous approach. https: ...

Navigating through an object using both dot and bracket notation

Can anyone shed some light on why I keep getting an 'undefined' message when trying to access object properties using dot notation like return contacts[i].prop;? However, if I use bracket notation like return contacts[i][prop];, it works fine an ...

combine the values from various keys into one cohesive array

Here is an array of objects that I need to manipulate: [ { "name": "product1", "Jan": 3, "Feb": 2, "Mar": 0, "Apr": 1, "May": 3, "Jun": 0, "Jul": 0, "Aug": 0, "Sep": 5, "Oct": 0, "Nov": 0, "Dec": 0 } ...

What is the best approach to display data in React fetched from an API request? If this is not the right method, what changes should be made to the JSX rendering to convert

As I begin my journey with React, I find myself questioning the best practices for displaying data. Should I always break down components into smaller ones rather than having one large component render everything? It seems like a good practice, but I' ...

Saving the subtracted value from a span into a cookie until the checkbox is unchecked - here's how to

I am working on a piece of code that includes numeric values within a span. When the checkbox is clicked, it subtracts 1 from the main value, essentially reducing the total value. How can I achieve this so that even after the form is submitted, the deducte ...

Error: Assertion Failed - The value being iterated over in #each must be an Array. Can someone please help me figure out what I'm

I am currently working on the TodoMVC tutorial for Ember and I have hit a roadblock. Specifically, I have defined 2 controllers. Here is my todos.js file: import Ember from "ember"; export default Ember.ArrayController.extend({ actions:{ crea ...

Every time I attempt to navigate to the login page, I find myself stuck in an endless loop

This code snippet demonstrates the router.beforeEach function in action. It checks if the client is authenticated, and if not, it redirects them to the login page. router.beforeEach(async (to, from, next) => { if ( to.name !== 'signup' || to ...

What is the best way to test a React component that includes a Router, Redux, and two Higher Order Components using Jest and Enzyme?

I'm currently facing a challenge with this issue. I have a React Component that is linked to React Router 4 and Redux store, and it's wrapped by two HOCs. It may sound complicated, but that's how it was implemented. Here's the export st ...

Following my ajax submission, the functionality of my bootstrap drop-down menu seems to have been compromised

I'm having an issue with my login page. After implementing Ajax code for the reset password feature, the dropdown menu on the login page doesn't work properly when wrong details are entered and the page reloads. I've tried using the $(' ...