Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data loaded with useEffect hook but don't display

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading