Page Refreshes on Route Change and Contexts get Updates

Viewed 31

When I click the sidebar button,(change the route), Page get Refreshed and useContext useEffect is called again. I have tried every possible variation of routing but the problem persisits.

This my App.js File

//App.js

  const { mode } = React.useContext(ThemeContext)

  if (window.location.pathname === ('/register')) {
    return <Register />
  }
  else if (window.location.pathname === "/") {
    return <Auth>
      <State>
        <Login />
      </State>
    </Auth>
  }

  return (
    <React.Fragment>
      <Auth>
        **<State>**
          <Router>

            <div className={`loaded ${mode ? "dark-layout" : "light-layout"}`}>
              <NavBar />
              <SideBar />
              <Routes>
                <Route path="/dashboard" element={<Dashboard />} />
                <Route path="/optionChain" element={<OptionChain />} />
                <Route path="/settings" element={<Settings />} />
              </Routes>

              <div className="app-content content ">
                <div className="content-wrapper container-xxl p-0">
                  <div className="content-body">
                    <Footer />
                  </div>
                </div>
              </div>
            </div>
          </Router>
        **</State>**
      </Auth>
    </React.Fragment >
  );

This is the rendering happening in index.js

//Index.js
root.render(
  <React.StrictMode>
    <Theme>
      <App />
    </Theme>
  </React.StrictMode>
);

And here in the SideBar All Links are defined. Extra Info: navClicked2 is used to change the color of clicked sideNav item. It is also using e.preventDefault()

//    SideBar Links
<li className={`nav-item ${navClicked2 ? 'active' : ''}`}>
      <Link className="d-flex align-items-center" to="/optionChain" onClick={hoverbtn2}>
       // {styling the side button here}
      </Link>
    </li>

The problem I am facing is that the Page is Refreshed when I change the route and the StateContext also gets refreshed. I used useRoutes so that my Login.js and Register components are inside the Routes and place BrowserRouter in index.js

return useRoutes([
    {
      path: '',
      children: [
        { path: '', element: <Login /> },
        { path: 'register', element: <Register /> }
      ],
    },

    {
      path: '',
      element: (
        <MainLayout />
      ),
      children: [
        { path: 'dashboard', element: <Dashboard /> },
        { path: 'strategy', element: <Strategy /> },
        { path: 'settings', element: <Settings /> },
      ],
    },

This solved the problem of Page Refresh also and Context Refresh also. But when I manually refresh the page from Chrome Refresh button, and then change the routes. Again it starts to behave as before, it starts to refresh the page on every Route Change. I Dont know why it is happening

In the State Context I have a WebSocket

const [client, setClient] = React.useState(new w3cwebsocket(`ws://${}/${operator && operator.username}/${operator && operator.password}`))


React.useEffect(() => {
    try {
        client.onopen = () => {
            console.log("WebSocket Client Connected");
        };
        client.onmessage = (message) => {
            const data = JSON.parse(message.data);
            console.log(data)
            data.nifty_data &&
                setData(
                    data.nifty_data,
                    setNiftyData,
                    setNiftyExpiry,
                    niftyData
                );
            data.bnf_data &&
                setData(
                    data.bnf_data,
                    setBankNiftyData,
                    setBankNiftyExpiry,
                    bankNiftyData
                );
            if (data.index_data) {
                setIndexData(data.index_data);
                setNiftyStrike(data.index_data.NIFTY[0][4]);
                setBankNiftyStrike(data.index_data.BANKNIFTY[0][4]);
            }
        };

        client.onerror = (message) => {
            console.log("Error " + message);
        };
        client.onclose = (message) => {
            console.log("Close " + message);
        };
    } catch (e) { console.log(e) }
}, []);


return (
    <StateContext.Provider value={{ niftyData, bankNiftyData, bankNiftyData, indexData, bankNiftyExpiry, niftyExpiry, bankNiftyStrike, niftyStrike }}>
        {props.children}
    </StateContext.Provider>
)

I am not able to understand why after reloading the page manually, why changing the routes from the sidebar starts to refresh the page again.

Please also tell me a way where Login and Register can be in the same Router and Navbar and Sidebar do not get rendered, but when Dashboard and other routes are rendered, Sidebar and Navbar should be rendered.

EDIT

The page is refreshing as if I clicked a href and page reloads. I am not able to understand why it is reloading because every redirect is in the <Link to="anyLocation">...</Link> tag. The State Context has wrapped the Router Component in App.js

1 Answers

remove window.location.pathname checks and use Protected routes instead.

Related