3

I have been looking around, but can't find a definite answer. I have wrapped my app in <AuthContext>, I have passed props and tried return <div>{props.user.username}</div> but nothing works, just getting the same TypeError: Cannot read property 'username' of undefined over and over again. Am I doing something fundamentally wrong here or is there a simple answer to this?

import React, { useContext } from "react";
import { AuthContext } from "../../context/auth";

const HeaderBar = (props) => {
    const {user: { user }} = useContext(AuthContext);

    if (user) {
        console.log(user.username); // Returns user in console log, so everything seems to be working fine
      }

    return <div>{user.username}</div> // Throws an error "TypeError: Cannot read property 'username' of undefined"
}

export default HeaderBar
Smlok
  • 598
  • 6
  • 19
  • Have you tried just assigning user to a simple variable instead of destructuring it immediately? It looks like you could be misunderstanding the data contract, as the console error is saying that `user` is undefined or at the very least the `username` key is not in the `user` object. So the first thing I'd check is if the `user` object is coming back as you expect – Sherman Hui Dec 25 '20 at 23:49
  • Does this answer your question? [Unable to render data in Reactjs](https://stackoverflow.com/questions/65415336/unable-to-render-data-in-reactjs) – jmargolisvt Dec 25 '20 at 23:55

1 Answers1

0

That seems pretty weird. However, I may have an explanation (but I'm not sure this will solve your problem).

You probably have something in your app that is changing, and make that component rerender. This means that you could have multiple logs in the console. The user can be defined when the component is rendered for the first time, and immediately change (for external reason ?), and changing the user variable to undefined.

Here are some tips you can use for debugging :

console.log(user.username) 
// throw an error if user is not defined, execution is stopped

console.log(user?.username) 
// returns undefined if user is not defined

console.log(user?.username ?? "username not defined") 
// return "username not defined" only if user is undefined or username is (undefined or null)

Using the 2nd or the 3rd syntaxe may help you avoid the error. You can try :

const HeaderBar = (props) => {
    const {user: { user }} = useContext(AuthContext);

    if (user) {
        console.log(user?.username ?? "username not defined");
      }

    return <div>{user?.username ?? "username not defined"}</div> // Cannot throw an error
}

This answer will not fix your problem but I hope it can help you ! ;)

Dony
  • 1,543
  • 2
  • 10
  • 25