In functional component useContext works in console.log but returns error on render

Viewed 315

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
1 Answers

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 ! ;)

Related