0

I am attempting to create a ProtectedRoutes component, however, I can't seem to get the auth state to update.

It should check if there is a cookie stored, and if so, set auth as true. Then if auth is true, it redirects to the auth component, otherwise to the landing/login page.

The auth page always redirects back to the landing page. The state is never updating to true. I can't figure out why.

ProtectedRoutes.js

import React, { Component, useState, useEffect } from "react";
import { Route, Navigate } from "react-router-dom";
import Cookies from "universal-cookie";
const cookies = new Cookies();


export default function ProtectedRoutes({component: Component, ...rest}) {
    const [auth, setAuth] = useState(false);
    //get cookie from browser if logged in
    const token = cookies.get("TOKEN");

    useEffect(() => {
        if (token) {
            setAuth(true);
            console.log(auth);
        }
    },[auth, token]);
    
    return auth ? <Component /> : <Navigate to="/" />
}

App.js

import { Container, Col, Row } from "react-bootstrap";
import "./App.css";
import Register from "./Register";
import Login from "./Login";
import { Routes, Route } from "react-router-dom";
import Account from "./Account";
import FreeComponent from "./FreeComponent";
import AuthComponent from "./AuthComponent";
import Private from "./ProtectedRoutes";
import ProtectedRoutes from "./ProtectedRoutes";

function App() {
  return (
    <Container>
      <Row>
        <Col className="text-center">
          <h1 className="header">React Authentication Tutorial</h1>

          <section id="navigation">
            <a href="/">Home</a>
            <a href="/free">Free Component</a>
            <a href="/auth">Auth Component</a>
          </section>
        </Col>
      </Row>
      
      {/* Routes */ }
      <Routes>
        <Route exact path="/" element={ <Account /> } />
        <Route exact path="/free" element={ <FreeComponent /> } />
        <Route path="/auth" element={<ProtectedRoutes component={AuthComponent} />} />
      </Routes>
    </Container>
  );
}

export default App;

AuthComponent.js

import React from 'react';

export default function AuthComponent() {
    return (
        <div>
            <h1 className="text-center">Auth Component</h1>
        </div>
    );
}
Sara
  • 79
  • 8
  • Don't call `setAuth()` in an effect hook that lists `auth` as a dependency, you could enter an infinite loop – Phil Feb 07 '22 at 02:51
  • I removed auth from the dependencies. I still can't get setAuth to do anything. – Sara Feb 07 '22 at 02:55
  • 1
    setting a state does not affect the local variable in the current control flow. Instead, the state change will cause the whole render function to be called again and receive the new value from the `useState()` call. – Christoph Burschka Feb 07 '22 at 02:59
  • Is it possible to make this work the way I'm trying to? – Sara Feb 07 '22 at 03:05

0 Answers0