I'm receiving a typeerror when trying to access the uid property of null, even though I don't have any asynchronous code and the users are logged

I am currently working on developing a user profile edit page that redirects users to their unique profile after logging in. However, I keep encountering an error that says Uncaught (in promise) TypeError: Cannot read properties of null (reading 'uid'). Despite confirming that the user is logged in and not using asynchronous code, I am puzzled by this issue. It seems like the uid might not be passing through before the function executes. Below is the vue.js script code responsible for displaying the profiles.

<script>

import getCollection from '../Composables/getCollection';
import getUser from '../Composables/getUser';
import getPremium from "../Composables/getPremium.js";

const {Premium, error, load} = getPremium();
load();





export default{
   
 
    
  setup() {
    const { user } = getUser()
    const { documents: Profile } = getCollection(
      'Premium', 
      ['userId', '==', user.value.uid]
    )
    console.log(Profile)

    return { Profile }
  }
}


</script>


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

<div v-if="Profile" class="Profile">
  <p class="text-5xl text-red-700 font-serif">Your Profile Statistics</p>
<div v-for =" Premium in Premium" :key="Premium.id">
<p class="text-5xl text-red-700 font-serif">Your Profile Statistics</p>
<p class="text-5xl text-red-700 font-serif">{{ Premium.name }}</p>
<br><br>
</template>

This is where my getUser.js page comes into play.

import { ref } from 'vue'
import { projectAuth } from '../firebase/config'

// refs
const user = ref(projectAuth.currentUser)

// auth changes
projectAuth.onAuthStateChanged(_user => {
  console.log('User state change. Current user is:', _user)
  user.value = _user
});

const getUser = () => {
  return { user } 
}

export default getUser

And here is my getCollection.js page.

import { ref, watchEffect } from 'vue'
import { projectFirestore } from '../firebase/config'

const getCollection = (collection, query) => {

  const documents = ref(null)
  const error = ref(null)

  // register the firestore collection reference
  let collectionRef = projectFirestore.collection(collection)
    .orderBy('createdAt')

  if (query) {
    collectionRef = collectionRef.where(...query)
  }

  const unsub = collectionRef.onSnapshot(snap => {
    let results = []
    snap.docs.forEach(doc => {
      // must wait for the server to create the timestamp & send it back
      doc.data().createdAt && results.push({...doc.data(), id: doc.id})
    });
    
    // update values
    documents.value = results
    error.value = null
  }, err => {
    console.log(err.message)
    documents.value = null
    error.value = 'could not fetch the data'
  })

  watchEffect((onInvalidate) => {
    onInvalidate(() => unsub());
  });

  return { error, documents }
}

export default getCollection

Despite ruling out any async functions or login issues, I remain stuck with the same error. I have compared my code with examples and even attempted computing functions, but to no avail. Any assistance on resolving this matter would be highly appreciated. Thank you.

Answer №1

It seems that the getUser function is likely causing the delay as it is asynchronous. The origin of this function in the provided code is unclear, but it appears to return a promise that should be awaited. To handle this, you can implement promise chaining like so:

setup() {
    let Profile = null;

    getUser().then(data => {
        const user = data.user;
        const { documents } = getCollection(
             'Premium', 
             ['userId', '==', user.value.uid]
        )
        Profile = documents;
    }).catch(err => {
        console.log(err);
    })

    console.log(Profile)

    return { Profile }
  }
}

The getCollection function also appears to be performing a server call and may be asynchronous.

Answer №2

Setting my profile as premium was crucial for resolving the issue.

<script>

import getCollection from '../Composables/getCollection';
import getUser from '../Composables/getUser';
import getPremium from "../Composables/getPremium.js";

const {Premium, error, load} = getPremium();
load();





export default{
   
 
    
  setup() {
    const { user } = getUser()
    const { documents: Premium } = getCollection(
      'Premium', 
      ['userId', '==', user.value.uid]
    )
    console.log(Premium)

    return { Premium }
  }
}


</script>


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

<div v-if="Premium" class="Profile">
  <p class="text-5xl text-red-700 font-serif">Your Profile Statistics</p>
<div v-for =" Premium in Premium" :key="Premium.id">
<p class="text-5xl text-red-700 font-serif">Your Profile Statistics</p>
<p class="text-5xl text-red-700 font-serif">{{ Premium.name }}</p>
<br><br>
</template>

Once I made this change, the problem was resolved.

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

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...

When loading a page for the first time, the Vue.js transition does not take effect

After setting up a navbar that switches between two components, I encountered an issue with the fade-in animation not running when the page is first opened. The animation only works when using the navbar links to switch components. Any suggestions on how t ...

changing up the format of nested blockquotes

My website includes various text features, which means that nested blockquotes are a possibility. I am now curious if it is feasible to style nested blockquotes differently from each other! blockquote{ background-color:#666; color:#fff; border ...

Storing user and message data with LocalStorage technology

Seeking advice on a straightforward approach to storing user data and messages. My idea is to use unique key values, such as random tokens (Ynjk_nkjSNKJN) for users, and real ids (1,2,3) for messages. Has anyone encountered this issue before? The goal is ...

What is the best way to create a delay so that it only appears after 16 seconds have elapsed?

Is there a way to delay the appearance of the sliding box until 16 seconds have passed? <script type="text/javascript"> $(function() { $(window).scroll(function(){ var distanceTop = $('#last').offset().top - $(window).height(); ...

Why does my jQuery code target all the text values?

Looking to grab a specific table cell number and multiply it by an input value on focusout, but having trouble with the selector grabbing all cells with "front" in the name. Check out the code below: jquery $(document).ready(function(){ $(".percent") ...

"Utilizing jQuery's AJAX POST method with PHP is successful, while using XMLHttpRequest is not yielding

Currently in the process of revamping my existing code to transition from jQuery's AJAX function to using XMLHttpRequest in vanilla JS. My understanding is that the following code snippets should be equivalent. However, while the jQuery version functi ...

Combining various data types within a single field in BigQuery

Is it feasible to specify a table schema with a field that allows for multiple data types? For instance: BIGQUERY TABLE SCHEMA schema: [{ name: 'field1', type: 'string', }, { name: 'field2', type: &apo ...

The hover effect is not functioning upon loading

Demo: http://jsbin.com/afixay/3/edit 1) Hover over the red box. 2) Without moving the cursor, press ctrl+r to reload the page. 3) No alert will appear. However, an alert will pop up once you move the cursor away and hover back over the box. The issue h ...

Transform input string containing newline characters into separate paragraphs

I utilize Contentful CMS for content management and fetch the content through their API. When the content is fetched, it comes in as a JSON object. One of the keys within this object pertains to the main text block for the entry I am retrieving. This stri ...

Display a webpage containing error messages and user input that can be sent back to the AJAX request

My form collects user information such as name, surname, etc. Here is an example of one input field: <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" value= ...

Is it possible for Angular.js timer finish event not to trigger data binding correctly?

I've been working on an AngularJS application that functions as a quiz by displaying pictures and prompting users to select the correct answer by clicking a button. The app is designed to store the user's answers in an object. Everything seems t ...

Having trouble triggering a click event with React testing library?

I am working with a <Select/> component as shown in the image below. App.tsx import React, { useState, ChangeEvent } from "react"; import MySelect from "./MySelect"; export default function App() { const [countryCode, setCoun ...

Tips for successfully transferring values from an onclick event in JavaScript to a jQuery function

I am encountering a challenge with an image that has an onclick function associated with it. <img id='1213' src='img/heart.png' onclick='heart(this.id)'> This particular function needs to be triggered : function heart ...

When the "ok" button is clicked in a custom confirmation box, the function will return

When the first button is clicked, I validate certain text boxes and then call Confirm() to display a confirmation box. I want it to return true to the calling function when "ok" is clicked and for control to go back to the UI to proceed ...

Can you please explain the purpose of this function?

I came across this code snippet on a website and I'm curious about its function and purpose. While I'm familiar with PHP, HTML, CSS, and JavaScript, I haven't had the chance to learn JQUERY and AJAX yet. Specifically, I'm interested in ...

The function .load callback was triggered on five separate occasions

I'm currently working with the code below and I have a feeling that I'm overlooking something important but just can't seem to figure it out. Basically, when the user clicks a button, a fragment of the page is loaded. Once this loading is s ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Conditional rendering is effective for displaying a form item based on certain conditions, but it may not be as effective for

I want a textarea element to appear or disappear based on the selected state of the radio buttons before it. If "no" is chosen, the textarea will be hidden, and if "yes" is chosen, the textarea will become visible. <fieldset class="input-group form-che ...

Make Fomantic-UI (Angular-JS) sidebar scroll independently

Is there a way to make a sidebar scroll independently of the content it pushes? Currently, my page is structured like this: -------------------------- |[button] Header | -------------------------- |S | Main content | |i | ...