October 25, 2024
Chicago 12, Melborne City, USA
javascript

Why is my React component being redirected to Login Component?


I have a react component inside a protected route. When I just render the component without the useEffect, it renders, but when I add the axios request, it redirects me to the login component, even though the user is authenticated and logged in. authenticated state comes back true. I’m not sure why it would redirect to log in if I am authenticated and logged in. When I run the API endpoint in Postman, it returns the user data.

import { useState, useContext, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import axios from "../api/axiosInstance";

import axiosInstance from "../api/axiosInstance";
axios.defaults.withCredentials = true;

export default function Profile() {
  const { profile_id } = useParams();
  const [profile, setProfile] = useState([]);

  const profileUrl = `/profile/${profile_id}`;

  useEffect(() => {
    fetchProfileDetails();
  }, [profile_id]);

  const fetchProfileDetails = async () => {
    try {
      const response = await axiosInstance.get(profileUrl);
      setProfile(response.data);
      console.log(response.data);
    } catch (error) {
      console.log(error);
    }
    
  }

  return (
    <>
    <p>PROFILE PAGE OF {profile}</p>
    </>
  );
}

My Routes:

<Routes>
          <Route path="/" element={<Home />} exact />
          <Route path="/login" element={<Login />} />
          <Route path="/register" element={<Register />} />
          <Route path="/page-not-found" element={<PageNotFound />} />
          <Route element={<ProtectedRoute />}>
            <Route element={<Layout />}>
              <Route path="/feed" element={<Feed />} />
              <Route path="/profile/:profile_id" element={<Profile />} />
              <Route path="/logout" />
            </Route> {/* End of Layout Container */}
          </Route> {/* End of ProtectedRoute container */}
      </Routes>

My ProtectedRoute:

import { Navigate, Outlet, useLocation } from 'react-router-dom';
import { AppContext } from "../Context/AppContext";
import { useContext } from 'react';
import Spinner from './Spinner';

function ProtectedRoute() {
  const location = useLocation();
  const {authenticated} = useContext(AppContext);

  if (authenticated === null) {
    <Spinner />
  }

  return authenticated ? (
    <Outlet />
  ) : (
    <Navigate to="/login" replace state={{ from: location }} />
  );
}

export default ProtectedRoute;



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video