theall-knowing's avatar

Component disappear when use Navigate() in ReactJS

Hi guys, I'm facing with this issue. When I'm using Navigate to redirect to another page, it doesn't load parent component (must be refreshed page to display properly). However, with "window.location.href" it works normally. I'm using useRoutes() form react router v6. Here my route file and related file.

22b2cf6ac29064598dec2044a6d0c4d5.png My page when be refreshed or use with "window.location.href". bf2611055343b957f2149e7a2a343da5.png 66bead6ae0d3ed7a0426ae45e52819ad.png But it seems doesn't load element: <FullLayout /> when use with navigate("/home");

//main.tsx
import { Suspense } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
import "@assets/scss/app.scss";
import "@assets/scss/icons.scss";
import reportWebVitals from "@/reportWebVitals";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { persistor, store } from "./configs/storeConfig.js";
import Loader from "./layouts/loader/Loader.js";

const rootElement = document.getElementById("root") as HTMLElement;
const root = createRoot(rootElement);
root.render(
  <Suspense fallback={<Loader />}>
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </PersistGate>
    </Provider>
  </Suspense>
);
reportWebVitals();
//app.tsx
import { useRoutes } from "react-router-dom";
import Themeroutes from "./routes/Router";

const App = () => {
  const routing = useRoutes(Themeroutes);

  return <div className="wrapper">{routing}</div>;
};

export default App;
//Router.tsx
import Icons from "@components/dashboard/Icons";
import MdiIcon from "@components/dashboard/MdiIcon";
import { AccountManagementRoutes } from "@modules/account_management/routes";
import { TaxInvoiceRoutes } from "@modules/bill_management/routes";
import { BusinessManagementRoutes } from "@modules/business_management/routes";
import { CategoryManagementRoutes } from "@modules/category_management/routes";
import { ConsultationRoutes } from "@modules/consultation/routes";
import { NamePlateRoutes } from "@modules/nameplate_management/routes";
import { QuoteRoutes } from "@modules/quote/routes";
import { UponContactRoutes } from "@modules/upon_contract/routes";
import { WaitingContactRoutes } from "@modules/waiting_contract/routes";
import { WaitingQuoteRoutes } from "@modules/waiting_quote/routes";
import { WaitingReceptionRoutes } from "@modules/waiting_reception/routes";
import { WriteAndSubmitRoutes } from "@modules/write_and_submit/routes";
import { BranchManagementRoutes } from "@modules/branch_management/routes";
import { lazy } from "react";
import { Navigate } from "react-router-dom";
import { EmployeeManagementRoutes } from "@modules/employee_management/routes";
import { DepartmentManagementRoutes } from "@modules/department_management/routes";
const LoginPage = lazy(() => import("@modules/auth/LoginPage"));
const FullLayout = lazy(() => import("../layouts/FullLayout"));
const HomePage = lazy(() => import("../modules/home/HomePage"));
const NotFoundPage = lazy(() => import("../components/NotFoundPage"));
/*****Routes******/
const ThemeRoutes = [
  {
    path: "/",
    element: <FullLayout />,
    children: [
      { path: "/", element: <Navigate to="/home" /> },
      { path: "/home", exact: true, element: <HomePage /> },
      { path: "/manager/", element: <Navigate to="/home" /> },
      { path: "/manager/home", exact: true, element: <HomePage /> },
      ...ConsultationRoutes,
      ...WaitingQuoteRoutes,
      ...QuoteRoutes,
      ...WaitingContactRoutes,
      ...UponContactRoutes,
      ...WaitingReceptionRoutes,
      ...WriteAndSubmitRoutes,
      ...TaxInvoiceRoutes,
      ...NamePlateRoutes,
      ...AccountManagementRoutes,
      ...BusinessManagementRoutes,
      ...CategoryManagementRoutes,
      ...BranchManagementRoutes,
      ...EmployeeManagementRoutes,
      ...DepartmentManagementRoutes,
      {
        path: "/icons",
        exact: true,
        element: (
          <>
            <Icons />
            <MdiIcon />
          </>
        ),
      },
      { path: "*", exact: true, element: <NotFoundPage /> },
    ],
  },
  {
    path: "/login",
    element: <LoginPage />,
  },
  {
    path: "/manager/login",
    element: <LoginPage />,
  },
];

export default ThemeRoutes;
//Login.tsx
import { useLocation, useNavigate } from "react-router-dom";
import Logo from "@assets/images/admin/logo.png";
import background from "@assets/images/admin/bg-login.jpg";
import { useDispatch, useSelector } from "react-redux";
import { login } from "../redux/action";
import { Dispatch } from "redux";
import { AuthStore } from "../utils/types";
import { useEffect, useState } from "react";
function Login() {
  const userInfo = useSelector((state: AuthStore) => state.auth.userInfo);
  const navigate = useNavigate();
  // if (userInfo?.role) {
  //   return window.location.href = "/home";
  // }
  useEffect(() => {
    if (userInfo?.role) {
      navigate("/home");
    }
},[]);
  const dispatch: Dispatch<any> = useDispatch();
  const location = useLocation();
  const loading = useSelector((state: AuthStore) => state.auth.loading);
  const [state, setState] = useState<{ [key: string]: any }>({});
  const handleLogin = (e: any) => {
    e.preventDefault();
    dispatch(
      login({
        user_id: state.user_id,
        user_pw: state.user_pw,
        isManager: location.pathname.includes("/manager"),
      })
    );
  };

  const handleChange = (e: any) => {
    const { name, value } = e.target;
    setState({
      ...state,
      [name]: value,
    });
  };

  return (
    <div className="bk_box" style={{ backgroundImage: `url(${background})` }}>
      <div className="login_wrap">
        <div className="login_top">
          <img role="button" src={Logo} alt="" />
          <h2>
            세이프어스 ERP시스템에 오신것을 <br />
            환영합니다.
          </h2>
        </div>
        <div className="login_content">
          <form
            action="https://eddypandamall.com/AdmMaster/login_check.php"
            method="post"
            name="loginForm"
          >
            <input
              type="text"
              name="user_id"
              placeholder="아이디를 입력해주세요."
              onChange={handleChange}
            />
            <input
              type="password"
              name="user_pw"
              placeholder="비밀번호를 입력해주세요."
              onChange={handleChange}
            />
            <div className="save_id">
              <input
                type="checkbox"
                name="saveId"
                id="save_id"
                className="input_checkbox"
              />
              <label htmlFor="save_id">ID저장</label>
            </div>
            <button className="login_btn" onClick={handleLogin}>
              {loading && <i className="mdi mdi-loading mdi-spin"></i>} 로그인
            </button>
          </form>
          <div className="info">
            <p>FAX : 02.3439.0773 / Email : [email protected]</p>
            <p>고객센터 : 02.3667.0774</p>
          </div>
        </div>
        <div className="copy">
          <p>designed by uwal communication</p>
        </div>
      </div>
    </div>
  );
}

export default Login;

Here my all source code. Does anyone have any idea? Please help me. Thank guys so much.

0 likes
0 replies

Please or to participate in this conversation.