Error: Attempting to access properties of an undefined value while retrieving data from Firebase

Struggling with displaying data in my NextJS app.

Data is being fetched from Firebase, and the interface structure is as follows:

export default interface IUser {
  name: string;
  email: string;
  uid: string;
  profileImageURL: string;
  publicData: {
    phone: string;
    address: string;
  }
}

When accessing users/[id]/page.tsx, data is fetched using the following code:


const [userData, setUserData] = useState({} as IUser);

    useEffect(() => {

      const fetchData = async () => {
        try {
          setIsLoading(true);
          const fetchedUserData = await fetchUserData(params.id)
          .then((data) => {
            setUserData(data)
            setIsLoading(false);
          })
        } catch (error) {
          console.error('Error fetching data:', error);
        }
      };
    
      fetchData();
    }, []);

While attempting to display the data, everything within publicData displays correctly, such as name and email. However, trying to access and display userData.publicData.address results in an error

TypeError: Cannot read properties of undefined (reading 'address')

Unsure about the cause of this issue, as the console shows no problem with the data. Maybe it's related to the User interface?

Appreciate any tips or solutions you can provide. Thank you!

UPDATE Here's a screenshot of the firebase structure https://i.sstatic.net/WxyNTSvw.png

Also including the code for fetchUserData

import IUser from "../interfaces/User";
import { getCache, setCache } from "./cache";

export const fetchUserData = async (uid: string): Promise<IUser> => {

    const cacheKey = 'userData_' + uid;
    const cachedData = getCache(cacheKey);

  if (cachedData) {
    console.log('Returning cached data:', cachedData);
    return cachedData as IUser;
  }

    const response = await fetch('https://dev/auth/user?id=' + uid,
        {
        method: 'get',
        headers: {
            'Content-type': 'application/json'
        }
    })
    if (!response.ok) {
        throw new Error("Failed to fetch user data");
    }
const data: IUser = await response.json();
console.log('Fetched data:', data);
setCache(cacheKey, data);

return data;
};

Answer №1

The reason this issue is occurring is due to not checking if the data is available before trying to display or use it. Retrieving data can take some time, so it's important to add a condition to verify if the data has been fetched before using it. For instance, in React, when rendering you can implement:

userData?.length > 0 && userData?.map(user => {
    // Code to render the data
});

Don't forget to include '?' before the dot to prevent any error screens from appearing. This precaution will ensure that your app doesn't crash.

I hope this explanation proves helpful. Thank you!

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

Guidelines for returning an object upon finishing the .map function within a promise-based function in Node.js

While working on server-side code using nodejs, I have encountered an issue with the .map() method inside a Promise. The problem is that the method returns a value before the .map() function completes its execution successfully. Here's the snippet of ...

Combining and mapping arrays in Javascript to form a single object

I am using the following firebase function this.sensorService.getTest() .snapshotChanges() .pipe( map(actions => actions.map(a => ({ [a.payload.key]: a.payload.val() }))) ).subscribe(sensors => { ...

Do we need a peer dependency specifically for TypeScript typings or is it optional?

My TypeScript library includes a React component, and one of the optional features allows users to pass an instance of a Redux store as a prop for Redux integration. <Component reduxStore={store}></Component> Since this feature is optional, I ...

React function causing website to freeze upon dispatch

I created a function in the child component to handle checkbox selection and trigger setDispatch(true). Unfortunately, whenever I check the checkbox, the website freezes and stops responding until I close and reopen it. Here is the function: const [ ...

Utilizing a particular Google font site-wide in a Next.js project, restricted to only the default route

My goal is to implement the 'Roboto' font globally in my Next.js project. Below is my main layout file where I attempted to do so following the documentation provided. import type { Metadata } from "next"; import { Roboto } from "n ...

Trouble with Firebase/Firestore documentation queries in JavaScript

Having trouble using the new Firestore system. I'm trying to retrieve a Collection of all users and go through it, but I can't seem to make it work. db.collection("users").get().then(function(querySnapshot){ console.log(querySnapshot.dat ...

The text cycling component in Next.js remains stagnant and never refreshes

I've encountered a challenge while working on a component that I initially thought would be straightforward: it's supposed to take an array of strings and update the text inside the div of the component every three seconds with the next item in t ...

Step-by-step guide on connecting to a MySQL database for Next.js using the .env file

const pool = mysql.createPool({ connectionLimit: 100, host: process.env.NEXT_PUBLIC_MYSQL_HOST, user: process.env.NEXT_PUBLIC_MYSQL_USER, password: process.env.NEXT_PUBLIC_MYSQL_PASSWORD, database: process.env.NEXT_PUBLIC_MYSQL_DATABASE ...

What is the method for inserting two dashes within a number?

For the output, I am looking to showcase a number in the following format => 979-9638403-03. At present, the number appears like this => 979963840303. portfolio.ts export class Portfolio { ... DEPO: number; /* DEPO */ const ...

After upgrading from Next.js 14.1.0 to 14.1.4, I encountered an error stating that the session cookie exceeds the allowed 4096 bytes limit in Next Auth

I recently updated my NextJs frontend to version 14.1.4 and encountered an authentication API error when using Next-Auth with Express as the backend. Reverting back to the previous version (14.1.0) resolved the error, but now I am facing a new issue while ...

A critical error has occurred: RangeError - The maximum call stack size has been exceeded while trying to

After attempting to filter a list of titles using Ng2SearchPipeModule, I imported the module in app.module.ts and created a new searchbar component. searchbar.component.ts import { FirebaseService } from './../../firebase.service'; import { Ang ...

The information displayed in Next.js appears in the form of an array, which is distinct from the JSON object provided by the API

I am retrieving data from a Laravel API using getServerSideProps(): This is the method I use to fetch the data: function Product({ data }) { console.log(data); return ( <div>Hello</div> ) } export async function getServerSidePr ...

What steps can be taken to ensure a user remains logged in even after a page reload in a Next.js app utilizing Firebase authentication?

I have implemented Firebase authentication for user login using GoogleAuthProvider. However, I am encountering an issue where the user gets logged out on page reload. Is there a way to persist the user without storing any credentials in localStorage? Belo ...

Type ' ' cannot be assigned to type ''..ts(2322) ANOTHA ONE

Being a beginner in TypeScript and currently learning about enums, I encountered an error with the following example code that I cannot seem to understand. Here's the code snippet: enum Status { SUCCESS = 'success', FAILED = 'fa ...

Struggle with typescript integration with emotion and styled components

Issue Description: I encountered an issue while working with typescript and emotion/styled libraries. When attempting to specify the type of the parent component that wraps a styled component, I faced difficulties. The scenario involves a parent componen ...

How can we accurately identify a device in Next.js SSR?

Currently, I am utilizing <MobileLayout /> and <DesktopLayout /> alongside Next.js for Server Side Rendering. Upon investigating, I observed that various prominent UI libraries feature mobile detection components such as the <Responsive /> ...

"Encountering a glitch in the Typescript/Node API where Express routes

Encountering a peculiar issue here - when attempting to import my router from an external file and add it as a route, I keep getting this unusual error where the string appears to be enclosed in double quotes. https://i.sstatic.net/nm9Wn.png ...

Troubleshooting the issue of process.nextTick not being recognized in Calgolia places.js

After successfully implementing Algolia's places.js in my Angular 7 project using NPM, I encountered an issue. I have integrated a form where one of the fields should be an input. <form [formGroup]="myForm"> <pre style="color: white; b ...

The Firebase cloud function will only activate when I manually input data into the Firestore database via the console

I'm having trouble getting my function to trigger when I programmatically add data to Firestore. It only seems to work when I manually add data through the console. Below is the code for my function: exports.updateFirestoreStatistics = functions.fir ...

Angular 2 code test coverage

Looking to calculate the code coverage of my Angular 2 code. Wondering if there are any plugins available for VS Code or WebStorm that can assist with this. My unit testing is done using Jasmine and Karma. ...