React conditional rendering not triggering? - javascript

I am trying to change the contents of my Navbar and my Router via useContext and conditional rendering.
This is my App.js:
import "./App.css";
import axios from "axios";
import { AuthContextProvider } from "./context/AuthContext";
import MyRouter from "./MyRouter";
axios.defaults.withCredentials = true;
function App() {
return (
<AuthContextProvider>
<MyRouter />
</AuthContextProvider>
);
}
export default App;
This is my Router:
import React, { useContext } from "react";
import AuthContext from "./context/AuthContext";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from "react-router-dom";
import MyNavBar from "./components/MyNavbar";
import "./App.css";
import Home from "./components/pages/Home";
import AboutUs from "./components/pages/AboutUs";
import Register from "./components/pages/Register";
import MyFooter from "./components/MyFooter";
import login from "./components/pages/login";
import ProfilePage from "./components/pages/ProfilePage";
function MyRouter() {
const { loggedIn } = useContext(AuthContext);
return (
<Router>
<MyNavBar />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/about-us" component={AboutUs} />
{loggedIn === false && (
<>
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={login} />
</>
)}
{loggedIn === true && (
<>
<Route exact path="/profile" component={ProfilePage} />
</>
)}
<Redirect to="404" />
</Switch>
<MyFooter />
</Router>
);
}
export default MyRouter;
My Navbar's conditional rendering works in the same way as the router. My problem is that neither of the conditional rendering fragments are working. For example, when my application starts, users are not logged in and the "loggedIn" value is false. With this logic, the routes "register" and "login" should be accessible, but they are not. Any advice or help would be greatly appreciated as I am quite new to using React.
Here is a screenshot of my console upon loading the application
This is my "AuthContext":
const AuthContext = createContext();
function AuthContextProvider(props) {
const [loggedIn, setLoggedIn] = useState(undefined);
async function getLoggedIn() {
const loggedInRes = await axios.get(
"http://localhost:5000/api/users/loggedIn"
);
setLoggedIn(loggedInRes.data);
}
useEffect(() => {
getLoggedIn();
}, []);
return (
<AuthContext.Provider value={{ loggedIn, getLoggedIn }}>
{props.children}
</AuthContext.Provider>
);
}
export default AuthContext;
export { AuthContextProvider };

Thanks for all the help guys, I learned a lot about the ProtectedRoute concept. My issue came from my Navigation Bar component. Instead of declaring my variable as an object, I declared loggedin like
const loggedIn = useContext(AuthContext);
All my errors were solved once I changed it to
const { loggedIn } = useContext(AuthContext);

Edited:
Instead of using your conditions in your main route, you can create a ProtectedRoute which Routes your component according to your condition.
import React, { useEffect } from "react";
import { Route, Redirect, useHistory } from "react-router-dom";
const ProtectedRoute = ({ component: Component, ...rest }) => {
const { loggedIn } = useContext(AuthContext);
return (
<Route
{...rest}
render={(props) =>
loggedIn() ? (
<Component {...props} />
) : (
<Redirect to='/login' />
)
}
/>
);
};
export default ProtectedRoute;
In your component you can change your logic with this:
<ProtectedRoute exact path="/" component={Home} />
<ProtectedRoute exact path="/about-us" component={AboutUs}/>
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={login} />
<ProtectedRoute exact path="/profile" component={ProfilePage} />
This means that if you wanna protect a route you should route it with ProtectedRoute otherwise classic react route.
You can read about that ProtectedRoute concept here

Related

React v6-Redux Create PrivateRoutes

Im trying to create a PrivateRoutes in addition to the regular routes.
After login, the page is successfully re-direct to /home, however when I tried to open /work, the page will go back to /home. all the data from state.valid is also shows "unidentified" in /work.
I figured it out that inside the privateRoutes it check if valid.isAuthenticated is true or not. However since. valid.isAuthenticated is set to false as initial value in reducer, everytime I open /home or /work, it re-render /login and then render /home or /work.
How do I fix to not to render /login before opening other pages?
Here is my PrivateRoutes.js
import React from "react";
import { useSelector } from "react-redux";
import { Navigate } from "react-router-dom";
const PrivateRoute = ({ children }) => {
const valid = useSelector((state) => state.valid);
return valid.isAuthenticated ? children : <Navigate to="/login" />;
};
export default PrivateRoute;
here is my AppRouter.js
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import PrivateRoute from "./PrivateRoute";
import App from "../components/App";
import Login from "../components/Login";
import HomePage from "../components/HomePage";
import WorkPage from "../components/WorkPage";
const AppRouter = () => (
<BrowserRouter>
<div>
<NavigationBar />
<div>
<Routes>
<Route path="/" element={<App />} exact />
<Route path="/login" element={<Login />} exact />
<Route path="/home" element={<PrivateRoute><HomePage /></PrivateRoute>} />
<Route path="/work" element={<PrivateRoute><WorkPage /></PrivateRoute>} />
</Routes>
</div>
</div>
</BrowserRouter>
);
export default AppRouter;
useEffect(() => {
if (valid.isAuthenticated) {
navigate("/home");
}
},[valid.isAuthenticated]);
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import PrivateRoute from "./PrivateRoute";
import App from "../components/App";
import Login from "../components/Login";
import HomePage from "../components/HomePage";
import WorkPage from "../components/WorkPage";
const AppRouter = () => {
useEffect(() => {
if (!valid.isAuthenticated) {
navigate("/login");
}
});
return (
<BrowserRouter>
<div>
<NavigationBar />
<div>
{valid.isAuthenticated ? <>
<Routes>
<Route path="/" element={<App />} exact />
<Route path="/home" element={<HomePage />} />
<Route path="/work" element={<WorkPage />} />
</Routes>
</>
:
<>
<Routes>
<Route path="/login" element={<Login />} exact />
</Routes>
</>
}
</div>
</div>
</BrowserRouter>
)
};
export default AppRouter;

Question about PrivateRoutes and to get navigated back to login page

Hi I need help getting my code to work so that when I try to log back in I won't be able to view the dashboard since I logged out. Right now its giving me a blank screen in my project and I think its because privateroute isn't a thing anymore? Not sure. This is my code in PrivateRoute.js:
import React, { Component } from 'react';
import { Route, Navigate } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
const PrivateRoute = ({ component: Component, auth: { isAuthenticated, loading },
...rest }) => (
<Route {...rest} render={props => !isAuthenticated && !loading ? (<Navigate to='/login' />) : (<Component {...props} />)} />
)
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired
};
const mapStatetoProps = state => ({
auth: state.auth
});
export default connect(mapStatetoProps)(PrivateRoute);
This is the code for the app.js:
import React, { Fragment, useEffect } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Landing from './components/layout/Landing';
import Register from './components/auth/Register';
import Login from './components/auth/Login';
import Alert from './components/layout/Alert';
import Dashboard from './components/dashboard/Dashboard';
import PrivateRoute from './components/routing/PrivateRoute';
// Redux
import { Provider } from 'react-redux';
import store from './store';
import { loadUser } from './actions/auth';
import setAuthToken from './utils/setAuthToken';
import './App.css';
if (localStorage.token) {
setAuthToken(localStorage.token);
}
const App = () => {
useEffect(() => {
store.dispatch(loadUser());
}, []);
return (
<Provider store={store}>
<Router>
<Fragment>
<Navbar />
<Routes>
<Route exact path='/' element={<Landing/>} />
</Routes>
<section className="container">
<Alert />
<Routes>
<Route exact path='/Register' element={<Register/>} />
<Route exact path='/Login' element={<Login/>} />
<PrivateRoute exact path='/dashboard' element={Dashboard} />
</Routes>
</section>
</Fragment>
</Router>
</Provider>
)};
export default App;
Please Help!
there is a recommended Protected Route implementation in the v6 react router docs you can follow.
DOCS IMPLEMENTATION
Your issue:
<Route {...rest} render={props => !isAuthenticated && !loading ?
(<Navigate to='/login' />) : (<Component {...props} />)} />
This Route is not up to date with v6, which I assume you are using, you need to update it.
Exact is also not supported anymore, there is no point in including it in your routes.
If you are not using v6 please update your post and include your react-router version.

react-router - handleLogin function

I have the following structure for my React.js application using React Router:
import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import './App.css';
import Landing from './components/Landing/Landing';
import Home from './components/Home/Home';
import { AuthProvider } from "./context/AuthProvider";
function App() {
const [user, setUser] = useState(false);
const handleLogin = e => {
e.preventDefault();
setUser(true);
}
return (
<div className="App">
<Router>
<AuthProvider>
<Routes>
<Route exact path='/' handleLogin={handleLogin}
render={props => <Landing {...props} user={user.toString()}
handleLogin={handleLogin} />} />
<Route exact path='/home' element={ <Home /> } />
</Routes>
</AuthProvider>
</Router>
</div>
)
}
export default App
I want to create a function called handleLogin which will invoke setUser and flip the user value to true when we click "Log In"
When I save it, It show a blank page and on console it display
Matched leaf route at location "/" does not have an element. This
means it will render an with a null value by default
resulting in an "empty" page.
What's the easiest and right way to do?

React Router Dom, protected route, getting ProtectedRoute is not a route

I created file auth.js file and ProtectedRoute.js in my application. Using JWT in API created a token and stored in local storage while login into my application. In my app.js imported the Authprovider and ProtectedRoute it shows error in route .please check my code and tell me where i made mistake
auth.js
import { useContext, createContext } from "react";
const AuthContext = createContext(null)
export const AuthProvider=({ children })=>{
const keyToken = localStorage.getItem("token");
const user = localStorage.getItem("name");
const userid = localStorage.getItem("id");
const pimg = localStorage.getItem("profile");
return(
<AuthContext.Provider value={{ keyToken,user,userid,pimg}}> {children}
</AuthContext.Provider>
)
}
export const useAuth = () => {
return useContext(AuthContext)
}
protectedRoute.js
import React from "react";
import { Navigate , Route } from "react-router-dom";
import {useAuth} from "./auth"
function ProtectedRoute({ component: Component, ...restOfProps }) {
const auth=useAuth();
const isAuthenticated = auth.keyToken;
console.log("this", isAuthenticated);
return (
<Route
{...restOfProps}
render={(props) =>
false ? <Component {...props} /> : <Navigate to="/login" />
}
/>
);
}
export default ProtectedRoute;
App.js
import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter as Router,Routes,Route} from 'react-router-dom';
import Login from "./components/SignIn";
import Category from "./pages/Category";
import Addcategory from "./pages/Addcategory";
import Subcategory from "./pages/Subcategory";
import Dashboard from "./pages/Dashboard";
import { Profile } from "./components/Profile";
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { AuthProvider} from "./components/authentication/auth";
import ProtectedRoute from "./components/authentication/protectedRoute";
function App() {
return (
<AuthProvider>
<Router>
<Routes>
<Route exact path='/' element={< Login />}></Route>
<Route exact path='/login' element={< Login />}></Route>
<ProtectedRoute exact path='/dashboard' element={ Dashboard}/>
{/*<Route exact path='/dashboard' element={< Dashboard />}></Route>*/}
<Route exact path='/category' element={< Category />}></Route>
<Route exact path='/categoryAdd' element={< Addcategory />}></Route>
<Route exact path='/subcategory' element={< Subcategory />}></Route>
<Route exact path='/profile' element={< Profile />}></Route>
</Routes>
<ToastContainer />
</Router>
</AuthProvider>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
export default App;
Error showing in console:
While what you did for ProtectedRoute I think would work for React Router Dom version 5, the version 6 is slightly different. Here is one way to do it (look at this example made by the library team to know more):
App.js:
function App() {
return (
<AuthProvider>
<Router>
<Routes>
<Route exact path='/dashboard' element={ <ProtectedRoute/>}/>
</Routes>
<ToastContainer />
</Router>
</AuthProvider>
);
}
ProtectedRoute.js:
function ProtectedRoute() {
const auth=useAuth();
const isAuthenticated = auth.keyToken;
if(isAuthenticated){
return <Dashboard/>
}
return (
<Navigate to="/login" />
);
}
export default ProtectedRoute;
You have mixed code of react-router-dom v5 and v6 you can read the migrate guide upgrading from v5
Can using Outlet to render ProtectedRoute as layout. Check this example
// ProtectedRoute.js
import { Navigate, Outlet } from 'react-router-dom';
export const ProtectedRoute = () => {
const location = useLocation();
const auth = useAuth();
return auth.isAuthenticated
? <Outlet />
: <Navigate to="/login" state={{ from: location }} replace />;
};
// App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
function App() {
return (
<AuthProvider>
<BrowserRouter>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/" element={<ProtectedRoute /> }>
<Route path='dashboard' element={<Dashboard />} />
<Route path='category' element={<Category />} />
// rest of your code
</Route>
</Routes>
<ToastContainer />
</BrowserRouter>
</AuthProvider>
);
}

React page won't stop refreshing

I recently deployed my site on to a work test server. When I was building everything locally it seemed to be working fine. However once I went ahead and deployed it, the site now auto refreshes none stop almost every second. I have gone through my code and the small changes I made and can't seem to find what the cause of the issue is and why the site on our work vps is now refreshing over and over again. I'm hoping someone might have some insight on this. I have gone ahead and posted my App.jsx, index.js, and Home.jsx below. Any insight on the matter would be really appreciated.
I should also note that I went back and moved everything back local to see if there is something I might have done before sending it to the server. It would seem when I run this locally there are zero issues. I've also tested this on multiple browsers and asked a few colleagues to take a look and it seems it continues to refresh every second for them too and on multiple browsers
App.jsx
import "./app.scss";
import Home from "./pages/home/Home";
import Register from "./pages/register/Register";
import Watch from "./pages/watch/Watch";
import Login from "./pages/login/Login";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from "react-router-dom";
import { useContext } from "react";
import { AuthContext } from "./context/authContext/AuthContext";
const App = () => {
const { user } = useContext(AuthContext);
return (
<Router>
<Switch>
<Route exact path="/">
{user ? <Home /> : <Redirect to="/register" />}
</Route>
<Route path="/register">
{!user ? <Register /> : <Redirect to="/" />}
</Route>
<Route path="/login">{!user ? <Login /> : <Redirect to="/" />}</Route>
{user && (
<>
<Route path="/movies">
<Home type="movie" />
</Route>
<Route path="/series">
<Home type="series" />
</Route>
<Route path="/watch">
<Watch />
</Route>
</>
)}
</Switch>
</Router>
);
};
export default App;
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { AuthContextProvider } from "./context/authContext/AuthContext";
ReactDOM.render(
<React.StrictMode>
<AuthContextProvider>
<App />
</AuthContextProvider>
</React.StrictMode>,
document.getElementById("root")
);
Home.jsx
import Navbar from "../../components/navbar/Navbar";
import Featured from "../../components/featured/Featured";
import "./home.scss";
import List from "../../components/list/List";
import { useEffect, useState } from "react";
import axios from "axios";
const Home = ({ type }) => {
const [lists, setLists] = useState([]);
const [genre, setGenre] = useState(null);
const axiosInstance = axios.create({
baseURL: process.env.REACT_APP_API_URL,
});
useEffect(() => {
const getRandomLists = async () => {
try {
const res = await axiosInstance.get(
`lists${type ? "?type=" + type : ""}${
genre ? "&genre=" + genre : ""
}`,
{
headers: {
token:
"Bearer " +
JSON.parse(localStorage.getItem("user")).accessToken,
},
}
);
setLists(res.data);
} catch (err) {
console.log(err);
}
};
getRandomLists();
}, [type, genre, axiosInstance]);
return (
<div className="home">
<Navbar />
<Featured type={type} setGenre={setGenre} />
{lists.map((list) => (
<List list={list} />
))}
</div>
);
};
export default Home;
A new axiosInstance is created on every render, and it triggers useEffect change.
Move the axiosInstance creation out of the component.
const axiosInstance = axios.create({
baseURL: process.env.REACT_APP_API_URL,
});
const Home = ({ type }) => {
const [lists, setLists] = useState([]);
const [genre, setGenre] = useState(null);
// stuff
};
Does the route that contains the component refreshes infinitely?
That is because React Refresh causes component remount each time the state changes. In your case, you are creating an axios instance 1) not only not storing it in the useState ( you create it as a plain variable ), 2) but also on each component render;
That causes the React Refresh to go crazy. The reason why it works on local might be related to some Webpack stuff, but that doesn't matter much as you should configure axios differently anyways.
Solution:
Why not to set up default configuration that will be common for all the requests through the application?
import "./app.scss";
import Home from "./pages/home/Home";
import Register from "./pages/register/Register";
import Watch from "./pages/watch/Watch";
import Login from "./pages/login/Login";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from "react-router-dom";
import { useEffect, useContext } from "react";
import { AuthContext } from "./context/authContext/AuthContext";
const App = () => {
useEffect( () => {
axios.defaults.baseURL = process.env.REACT_APP_API_URL;
}, [] )
const { user } = useContext(AuthContext);
return (
<Router>
<Switch>
<Route exact path="/">
{user ? <Home /> : <Redirect to="/register" />}
</Route>
<Route path="/register">
{!user ? <Register /> : <Redirect to="/" />}
</Route>
<Route path="/login">{!user ? <Login /> : <Redirect to="/" />}</Route>
{user && (
<>
<Route path="/movies">
<Home type="movie" />
</Route>
<Route path="/series">
<Home type="series" />
</Route>
<Route path="/watch">
<Watch />
</Route>
</>
)}
</Switch>
</Router>
);
};
export default App;
So that no instances are created, and defaults are configured correctly.
Then you use it like:
axios.post( '/someendpoint', { test : true } )
Let me know if it works!

Categories

Resources