The current user's name is appearing as "undefined" in NextJS

Launching straight into the query, I am facing an issue when using console.log(user);. It returns an object with a string value for displayName. However, upon running console.log(user.displayName);, it should display the value Agrim Singh (<-- I've entered this value). Instead, it throws an error message:

TypeError: Cannot read properties of null (reading 'displayName')

Here is a screenshot of the error: https://i.sstatic.net/cCUaF.png

Additionally, I am utilizing NextJS in conjunction with Firebase.

Below is the code snippet from the file [postid].jsx:

const post = ({ post, user }) => {
  const [name, setName] = useState("");
  const [addComment, setAddComment] = useState("");

  const router = useRouter();
  const { postid } = router.query;

  console.log(user); // <--- Working perfectly.
  console.log(user.displayName); // <--- Throwing error.

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!addComment || !name) {
      alert("Please fill all the fields proplerly!");
    } else {
      db.collection("posts").doc(postid).collection("comments").add({
        name: name, // <--- Please ignore this line for now
        comment: addComment,
      });
    }
  };
  return (
    <div className="post container text-center">
      <h2>{post.title}</h2>
      <h5>Created On - {new Date(post.createdAt).toDateString()}</h5>
      <br />
      <img src={post.imageUrl} alt={post.alt} />
      <br />
      <p>{post.description}</p>
      <br />
      <form>
        <div className="form-input">
          <input
            type="text"
            name="name"
            id="name"
            className="name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Enter Your Name"
          />
        </div>
        <div className="form-input">
          <textarea
            name="add-comment"
            id="add-comment"
            className="add-comment"
            value={addComment}
            onChange={(e) => setAddComment(e.target.value)}
            cols="100"
            rows="3"
            placeholder="Add your Comment"
          ></textarea>
        </div>
        <button onClick={handleSubmit} className="btn-warning">
          Submit
        </button>
      </form>

      <div className="comments">
        <p className="comment">
          <b>
            <i>Name</i>:
          </b>{" "}
          <span>Comment</span> {/* <--- I've not programmed this line because of the error. */}
        </p>
      </div>
    </div>
  );
};

export default post;

export async function getServerSideProps({ params }) {
  const result = await db.collection("posts").doc(params.postid).get();
  return {
    props: {
      post: {
        ...result.data(),
        createdAt: result.data().createdAt.toMillis(),
      },
    },
  };
}

I have passed the user prop to all files in the _app.js file.

Check out the code below:

export default function App({ Component, pageProps }) {
  const [user, setUser] = useState(null);
  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        setUser(user);
      } else {
        setUser(null);
      }
    });
  }, []);
  return (
    <div className="app">
      <div className="banner-div">
        <Navbar user={user} />
        <img src="/banner.jpg" alt="School Banner" className="banner" />
      </div>
      <Component {...pageProps} user={user} />
    </div>
  );
}

Edit: user.displayName functions correctly everywhere except in the [postid].jsx file.

Edit 2: Upon executing

console.log(user);

It displays both null and the object.

Refer to the image:https://i.sstatic.net/aBzXO.png

Answer №1

Success at last!

This solution worked wonders for me

const infoUser = user; // <--- "user" is the variable pulled from the file "_app.js"
console.log(infoUser?.name);

The console now displays the data.

The addition of ? made all the difference.

I'm curious to know why this solved the issue.

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

update the element that acts as the divider in a web address (Angular)

Is it possible to modify the separator character used when obtaining the URL parameters with route.queryParams.subscribe? Currently, Object.keys(params) separates the parameters using "&" as the separator. Is there a way to change this to use a differe ...

Ways to split images and text in list items using CSS

Can the text be formatted in a specific location on the page, separate from the image and heading? This is the HTML code I am currently using: <div class="tab-pane container fade" id="environmental"> <div class="row"> <div class="c ...

Is it possible to retrieve hash values through a regex loop?

Looking at the JSON object below, I am aiming to iterate over entries that match u[0-9][0-9][0-9]. While this answer on Stack Overflow comes close to what I want, my goal is to extract the hash values instead. Here's what happens when I attempt the f ...

Troubleshooting ThreeJS import issues in Vue test utilities using Jest

I'm currently facing a challenge with my Jest tests for a VueJS SPA after integrating Three.js into one of my components. While everything runs smoothly in the app, the tests fail with this error: /Users/Whomever/FE/node_modules/three/examples/jsm/con ...

Having issues with the functionality of my Vuejs filter in my code

Within my Vue.js code, I am facing an issue. I have questions retrieved from an API along with their respective categories stored in an array called 'questions'. My goal is to be able to filter the questions based on the category that is clicked. ...

Accessing state in a child component through props using "(this.props.(propName))" results in undefined value because of the usage of "This" keyword

Currently, I have a parent component that contains a state with a theme string. This setup is purely for testing purposes, so let's not delve too deep into its practicality at the moment! So far, here is the layout: The Parent Component holds the st ...

Get alerts from Twitter pushed to my site

Is it possible to create a web application that utilizes JavaScript to receive notifications from Twitter? I want my website app to send me notifications whenever a person I follow posts a new article. I'm having difficulty with this task and would gr ...

Is there a way to alter the variant or background of a clicked button exclusively through reactjs? If so, how can I make it happen?

My goal is to change the variant of a Material UI button from outlined to contained or simply change its background color when it is clicked. I am unable to use the onFocus property due to conflicts with another component. Here is my current method, but ...

Switch up the text within the URL of the background image

Simply put, this is the structure I have: <div id="RelatedPosts1"> <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-1.jpg)"></div> <div class="related-posts-thumb" style="background: url(http: ...

Tips for converting this ajax code to long polling

I am currently using this ajax code and I was wondering if anyone knows how to change it to long polling. Here is the code I am using: var chat = {} chat.fetchMessages = function () { $.ajax({ url: 'ajax/ajax/chat.php', type: 'PO ...

MYSQL table successfully created, however encountering a 500 error when attempting to post data

I've been working with the Node module KNEX for making MYSQL calls, and I'm trying to allow users to add their own custom tables. I have successfully added a database to MYSQL with all the necessary columns, but unfortunately, I keep encountering ...

Upon refreshing the page, next.js 13's useSession() function fails to fetch session information

Currently, I am working on replicating an ecommerce site using nextjs 13. On the order page, I am utilizing useSession from next-auth/react to check if a user is signed in or not. Everything works fine when I navigate to the page through a link, but if I r ...

Collapsible tree visualization in D3 experiences erratic behavior while zooming

After spending a considerable amount of time grappling with this issue, I find myself stuck. My objective is to construct a d3 collapsible tree, but every time I attempt to zoom in, the tree shifts to position 0,0. I've come across other queries like ...

Utilize Photoshop's Javascript feature to extract every layer within the currently active document

Looking for insights on a Photoshop scripting issue. I have written a solution but it's not producing the correct result. Can anyone provide feedback on what might be wrong with the code? The goal is to retrieve all the layers in a document. Here is ...

What steps should I take to create a plugin for a library if defining it as a peerDependency does not provide a specific implementation for me to work with?

Requirements for My Plugin: I'm currently in the process of developing a new plugin that is dependent on popularLibrary.js. Here are the key points about my plugin: It will not function properly if popularLibrary.js is missing. It is designed to wo ...

The jQuery newsfeed is powered by the $.each() method

I'm having trouble setting up a newsfeed on my website. It's supposed to display all the current news and exclude any expired ones. I have a webpage where I can add news, so the JSON data is constantly changing. Here's an example of the PHP ...

Tips for inserting a line break within a cell using the Excel4node library in a Node.js environment

I am struggling to add a multiline cell using the module excel4node. Despite consulting the documentation, I couldn't find any information on how to achieve this. I attempted to insert the escape sequence "\n", but it did not produce the desired ...

JavaScript comparing variables to nested object properties

items resembling this are heading my direction: var info = { a0: { name: 'lengthy title 0', var1_min: '10', var1_max: '99', select: ['alpha', 'gamma'], display: 'value0' }, b12: { ...

Calling a JavaScript function from server-side code (without using startup scripts)

In essence, my objective is as follows: Initiate deletion of a record upon button click. Delete the record only if a specific column (Location) is null (working perfectly). If the specific column is not null, prompt the user for confirmation before proce ...

Creating a duplicate object in a React component

I am currently developing a basic react application with inputs such as first name, last name, etc... The input states are managed using context api in the following context.js: import React, { useState } from "react"; export const FormContext ...