skip to Main Content

I am loading data from firebase in useEffect and I am trying to display it.

Data are loaded but don’t display. I don’t understand why.

UserDetails.js:

import React, { useEffect, useState } from 'react'

import { useParams } from "react-router-dom";

import base from '../base';

import { ref, onValue } from "firebase/database";

const UserDetails = () => {

  const { userId } = useParams();
  const [user, setUser] = useState()

  useEffect(() => {
    const usersRef = ref(base, '/users');

    onValue(usersRef, (snapshot) => {
      const users = snapshot.val();
      let user = {};
      if (users !== null) {
        user = users.filter(user => user.id == userId)[0]
        setUser({ user });
      }
    });
  }, [userId]);

  return (
    <>
      <p>Hello {user.first_name}</p>
    </>
  )
}

export default UserDetails

Error:

Cannot read properties of undefined (reading ‘first_name’)
TypeError: Cannot read properties of undefined (reading ‘first_name’)
at UserDetails

2

Answers


  1. user is already an object you just pass it to the setter function of the state you don’t need curly braces:

    setUser(user);
    
    <>
     <p>Hello {user?.first_name}</p>
    </>
    

    with

    setUser({ user });
    

    you are setting an object with a property user that is an object containing the user info so you have to access the user name this way:

    <p>Hello {user?.user?.first_name}</p>
    
    Login or Signup to reply.
  2. The effect does not fire until after the first render of your component. So on the first render, in the return statement user has whatever initial value it was assigned in useState, which here is undefined. This causes an error, as we’re trying to read a property of an undefined variable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search