Home > Mobile >  userData.name is not showing the user's name
userData.name is not showing the user's name

Time:06-26

I am learning MERN and I created a simple website on which you can log in and register.

The login and register functionality is working perfectly but my About page has some errors.

The about page matter is simple if you are not logged in (based on the token in the Cookies section) and you click on About it redirects you to the Login page and if you are logged in, it will show your details.

And when I get all the data from MongoDB I have stored it in a variable data. And I have stored all the data from data in a useState(); named userData.

When I console.log(userData); it shows me all the details that is good and when I console.log(userData.name), it shows the name of the user that is good too.

But when I give the same userData.name in h5, it shows me an error.

I have given like this: <h5>{userData.name}</h5>.

My full About.js code:

import React from 'react';
import agrim from "../images/agrim.jpeg";
import { useNavigate } from "react-router-dom";

const About = () => {

  const navigate = useNavigate();

  const [userData, setUserData] = React.useState();

  const callAboutPage = async () => {
    try {
      const res = await fetch("/about", {
        method: "GET",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        credentials: "include"
      });

      const data = await res.json();

      setUserData(data);

      if(!res.status === 200) {
        const error = new Error(`An Error Occurred: ${res.error}`);
        console.log(error);
        throw error;
      }
    } catch (error) {
      console.log(`An Error Occurred: ${error.message}`);
      navigate("/login");
    }
  }

  React.useEffect(() => {
    callAboutPage();
  }, [callAboutPage]);

  return (
    <>
      <div className="container emp-profile mt-4">
        <form method="GET">
          <div className="row">
            <div className="col-md-4">
              <div className="profile-img">
                <img src={agrim} alt="Agrim Singh" />
              </div>
            </div>

            <div className="col-md-6 profile-head">
              <h5 onClick={() => console.log(userData.name)}>{userData.name}</h5>
              <h6>Web Developer, Student</h6>
              <p>
                RANKINGS : <span>1/10</span>
              </p>

              <ul className="nav nav-tabs" role="tablist">
                <li className="nav-item">
                  <a
                    href="#home"
                    className="nav-link-active mr-4"
                    id="home-tab"
                    data-toggle="tab"
                    role="tab"
                  >
                    About
                  </a>
                </li>

                <li className="nav-item">
                  <a
                    href="#profile"
                    className="nav-link-active"
                    id="profile-tab"
                    data-toggle="tab"
                    role="tab"
                  >
                    Timeline
                  </a>
                </li>
              </ul>
            </div>
            <div className="col-md-2">
              <input type="submit" className="profile-edit-btn" name="btnAddMore" value="Edit Profile" />
            </div>
          </div>

          <div className="row">
            <div className="col-md-4">
              <div className="profile-work">
                <p>WORK LINK</p>
                <a href="https://www.youtube.com/channel/UCdfS-7bgMHA_x-0u7pxjZng" target="_youtube">Youtube</a> <br />
                <a href="https://instagram.com/ff_player.agrim" target="_instagram">Instagram</a> <br />
                <a href="https://gsonline.vercel.app/" target="_gsonline">GSOnine</a> <br />
                <a href="https://agrimpay-paymentapp.web.app/" target="_agrimpay">Agrim Pay</a> <br />
                <a href="https://mernagrimatechnical.herokuapp.com/" target="_agrimpay">Agrim Technical</a> <br />
                <a href="https://www.github.com/AgrimSingh421" target="_github">Github</a>
              </div>
            </div>

            <div className="col-md-8 pl-5 about-info">
              <div className="tab-content profile-tab" id="myTabContent">
                <div className="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
                  <div className="row">
                    <div className="col-md-6">
                      <label>User ID</label>
                    </div>
                    <div className="col-md-6">
                      <p>45899963254778996541</p>
                    </div>
                  </div>

                  <div className="row mt-3">
                    <div className="col-md-6">
                      <label>Name</label>
                    </div>
                    <div className="col-md-6">
                      <p>{userData.name}</p>
                    </div>
                  </div>

                  <div className="row mt-3">
                    <div className="col-md-6">
                      <label>Email</label>
                    </div>
                    <div className="col-md-6">
                      <p>[email protected]</p>
                    </div>
                  </div>

                  <div className="row mt-3">
                    <div className="col-md-6">
                      <label>Phone</label>
                    </div>
                    <div className="col-md-6">
                      <p>8996325410</p>
                    </div>
                  </div>

                  <div className="row mt-3">
                    <div className="col-md-6">
                      <label>Profession</label>
                    </div>
                    <div className="col-md-6">
                      <p>Web Developer, Student</p>
                    </div>
                  </div>
                </div>

                <div className="tab-pane fade show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
                  <div className="row">
                    <div className="col-md-6">
                      <label>Experience</label>
                    </div>
                    <div className="col-md-6">
                      <p>Intermediate</p>
                    </div>
                  </div>

                  <div className="row mt-3">
                    <div className="col-md-6">
                      <label>Hourly Rate</label>
                    </div>
                    <div className="col-md-6">
                      <p>₹599/hr</p>
                    </div>
                  </div>

                  <div className="row mt-3">
                    <div className="col-md-6">
                      <label>Total Projects</label>
                    </div>
                    <div className="col-md-6">
                      <p>24</p>
                    </div>
                  </div>

                  <div className="row mt-3">
                    <div className="col-md-6">
                      <label>Availibility</label>
                    </div>
                    <div className="col-md-6">
                      <p>10 Months</p>
                    </div>
                  </div>

                  <div className="row mt-3">
                    <div className="col-md-6">
                      <label>English Level</label>
                    </div>
                    <div className="col-md-6">
                      <p>Intermediate</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>
    </>
  );
};

export default About;

I have not given in other fields because if userData.name will be fine, others will also be good to go.

My full authenticate.js code:

//_ Requiring Modules
const jwt = require("jsonwebtoken");
const User = require("../model/userSchema");

//_ Making authenticate function to use in auth.js
const authenticate = async (req,  res, next) => {
    try {
        const token = req.cookies.jwtoken;    //_ Getting Token from cookies
        const verifyToken = jwt.verify(token, process.env.SECRET_KEY);    //_ Verifiying token and storing it into a variable

        const rootUser = await User.findOne({ _id: verifyToken._id, "tokens.token": token });    //_ If the token in the cookies section from the browser is matched from the token from the database, it means the user is available and we can show him his about page

        if(!rootUser) { throw new Error("User not found!") }

        //_ Getting all data
        req.token = token;
        req.rootUser = rootUser;
        req.userID = rootUser._id;

        next();    //_ Calling next() to do other things. Im simple words: AAGE BADHO AAGE!
    } catch (error) {
        res.status(401).send("Unauthorized: No token provided");
        console.log(`An Error Occurred: ${error.message}`);
    }
}

//_ Exporting authenticate function
module.exports = authenticate;

I have an auth.js file in which I am calling about page

router.get("/about", authenticate, (req, res) => {
    res.send(req.rootUser);
});

I have imported router like this:

const express = require("express");
const router = express.Router();

And I have exported router like this: module.exports = router;

Any help would be appreciated...

CodePudding user response:

You have to change the useState type:

const [userData, setUserData] = useState({}):
  • Related