Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
import React, { useState } from "react";
import { Link, useLocation } from "react-router-dom";
import { RiCloseCircleFill, RiNotificationLine } from "react-icons/ri";
import {
  RiHome2Fill,
  RiFile2Fill,
  RiHospitalFill,
  RiProfileFill,
  RiLogoutBoxFill,
} from "react-icons/ri";
import { useSelector } from "react-redux";

import "../Layout.css";

function Layout({ children }) {
  const [collapsed, setCollapsed] = useState(false);
  const { user } = useSelector((state) => state.userData) || {};
  const location = useLocation();
  console.log(user.isAdmin);
  const userMenu = [
    { name: "Home", path: "/", icon: RiHome2Fill },
    { name: "Appoint", path: "/appointments", icon: RiFile2Fill },
    { name: "Apply doctor", path: "/apply-doctor", icon: RiHospitalFill },
    { name: "Profile", path: "/profile", icon: RiProfileFill },
    { name: "Logout", path: "/logout", icon: RiLogoutBoxFill },
  ];

  const adminMenu = [
    { name: "Home", path: "/", icon: RiHome2Fill },
    { name: "users", path: "/users", icon: RiFile2Fill },
    { name: "doctors", path: "/doctors", icon: RiHospitalFill },
    { name: "Profile", path: "/profile", icon: RiProfileFill },
    { name: "Logout", path: "/logout", icon: RiLogoutBoxFill },
  ];

  const menuToBeRendered = () => {
    if (user && user.isAdmin) {
      return adminMenu;
    } else {
      return userMenu;
    }
  };

  const menuItems = menuToBeRendered().map((menu, index) => {
    const isactive = location.pathname === menu.path;
    const Icon = menu.icon;
    return (
      <Link key={index} to={menu.path}>
        <div className={`d-flex menu-item ${isactive && "active-menu-item"}`}>
          {collapsed ? (
            <Icon className="ri-icon" />
          ) : (
            <div className="d-flex">
              <Icon className="ri-icon" />
              <span>{menu.name}</span>
            </div>
          )}
        </div>
      </Link>
    );
  });

  return (
    <div className="main">
      <div className="d-flex layout">
        <div className={`sidebar ${collapsed ? "collapsed" : ""}`}>
          <div className="sidebar-header">
            <h3>SEVA</h3>
          </div>
          <div className="menu">{menuItems}</div>
        </div>
        <div className="content">
          <div className="header">
            <RiCloseCircleFill
              className="close-icon"
              onClick={() => setCollapsed(!collapsed)}
            />
            <div className="d-flex">
              <RiNotificationLine className="layout-action-icon" />
              {user && <Link to="/profile">{user.name}</Link>}
            </div>
          </div>
          <div className="body">{children}</div>
        </div>
      </div>
    </div>
  );
}

export default Layout;
import { configureStore } from "@reduxjs/toolkit";
import { combineReducers } from "@reduxjs/toolkit";
import { alertsSlice } from "./alertsSlice";
const rootReducer = combineReducers({ alerts: alertsSlice.reducer });
const store = configureStore({ reducer: rootReducer });
export default store;
const express = require("express");
const router = express.Router();
const User = require("../models/userModel");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const authmiddleware = require("../middlewares/authmiddleware");
router.post("/register", async (req, res) => {
try {
const userExists = await User.findOne({ email: req.body.email });
if (userExists) {
return res
.status(200)
.send({ message: "user exists alreayd", success: false });
}
const password = req.body.password;
const salt = await bcrypt.genSalt(10);
const hashedpassword = await bcrypt.hash(password, salt);

req.body.password = hashedpassword;
const newuser = new User(req.body);
await newuser.save();
res.status(200).send({ message: "user created", success: true });
} catch (error) {
console.log(error);
return res.status(500).send({ message: "Error", success: false, error });
}
});
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
if (!user) {
return res
.status(200)
.send({ message: "User do not exists", sucess: false });
}
const isMatch = await bcrypt.compare(req.body.password, user.password);
if (!isMatch) {
return res
.status(200)
.send({ message: "password is incorrect", success: false });
} else {
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: "1d",
});
res
.status(200)
.send({ message: "Login Successful", success: true, data: token });
}
} catch (error) {
console.log(error);
res
.status(500)
.send({ message: "Error Logging In", success: false, error });
}
});
router.post("/getuserinfo", authmiddleware, async (req, res) => {
try {
const user = await User.findOne({ _id: req.body.userId });
if (!user) {
return res
.status(200)
.send({ message: "User do not exists", sucess: false });
} else {
res.status(200).send({
success: true,
data: { name: user.name, email: user.email, isAdmin: user.isAdmin },
});
}
} catch (error) {
res
.status(500)
.send({ message: "Error gettin userinfo", success: false, error });
}
router.post("/apply-doctor-account", async (req, res) => {
try {
const newdoctor = new Doctor({ ...req.body, status: "pending" });
await newdoctor.save();
const adminUser = await User.findOne({ isAdmin: true });
const unseenNotifications = adminUser.unseenNotifications;
unseenNotifications.push({
type: "new-doctor-request",
message: `${newdoctor.firstName} ${newdoctor.lastName} has applied for a doctor account`,
data: {
doctorId: newdoctor._id,
name: newdoctor.firstName + " " + newdoctor.lastName,
},
onClickPath: "/admin/doctors",
});
await User.findByIdAndUpdate(adminUser._id, { unseenNotifications });
} catch (error) {
console.log(error);
return res
.status(500)
.send({ message: "Error applying doctor", success: false, error });
}
});
});

module.exports = router;
import React, { useState } from "react";
import { Link, useLocation } from "react-router-dom";
import { RiCloseCircleFill, RiNotificationLine } from "react-icons/ri";
import {
  RiHome2Fill,
  RiFile2Fill,
  RiHospitalFill,
  RiProfileFill,
  RiLogoutBoxFill,
} from "react-icons/ri";
import { useSelector } from "react-redux";

import "../Layout.css";

function Layout({ children }) {
  const [collapsed, setCollapsed] = useState(false);
  const { user } = useSelector((state) => state.userData) || {};
  const location = useLocation();
  console.log(user.isAdmin);
  const userMenu = [
    { name: "Home", path: "/", icon: RiHome2Fill },
    { name: "Appoint", path: "/appointments", icon: RiFile2Fill },
    { name: "Apply doctor", path: "/apply-doctor", icon: RiHospitalFill },
    { name: "Profile", path: "/profile", icon: RiProfileFill },
    { name: "Logout", path: "/logout", icon: RiLogoutBoxFill },
  ];

  const adminMenu = [
    { name: "Home", path: "/", icon: RiHome2Fill },
    { name: "users", path: "/users", icon: RiFile2Fill },
    { name: "doctors", path: "/doctors", icon: RiHospitalFill },
    { name: "Profile", path: "/profile", icon: RiProfileFill },
    { name: "Logout", path: "/logout", icon: RiLogoutBoxFill },
  ];

  const menuToBeRendered = () => {
    if (user && user.isAdmin) {
      return adminMenu;
    } else {
      return userMenu;
    }
  };

  const menuItems = menuToBeRendered().map((menu, index) => {
    const isactive = location.pathname === menu.path;
    const Icon = menu.icon;
    return (
      <Link key={index} to={menu.path}>
        <div className={`d-flex menu-item ${isactive && "active-menu-item"}`}>
          {collapsed ? (
            <Icon className="ri-icon" />
          ) : (
            <div className="d-flex">
              <Icon className="ri-icon" />
              <span>{menu.name}</span>
            </div>
          )}
        </div>
      </Link>
    );
  });

  return (
    <div className="main">
      <div className="d-flex layout">
        <div className={`sidebar ${collapsed ? "collapsed" : ""}`}>
          <div className="sidebar-header">
            <h3>SEVA</h3>
          </div>
          <div className="menu">{menuItems}</div>
        </div>
        <div className="content">
          <div className="header">
            <RiCloseCircleFill
              className="close-icon"
              onClick={() => setCollapsed(!collapsed)}
            />
            <div className="d-flex">
              <RiNotificationLine className="layout-action-icon" />
              {user && <Link to="/profile">{user.name}</Link>}
            </div>
          </div>
          <div className="body">{children}</div>
        </div>
      </div>
    </div>
  );
}

export default Layout;


What I have tried:

when i try to print the userschema it says that user is undefined
Posted
Comments
Richard MacCutchan 13-Mar-23 12:39pm    
It would help if you explained exactly where the error occurs in that code dump.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900