Home > Enterprise >  Many http requests are being made when I visit a React route even though only one request is being c
Many http requests are being made when I visit a React route even though only one request is being c

Time:01-08

Whenever I visit the "/" route and I go to the network section in inspect, I see a bunch of requests going to "/api/checkauth". I only call the request "/api/checkauth" once, when I visit the "/" route. Maybe its something to do with element={...}. I don't know how to fix this issue.

This what I see in the network section when I visit it once

import './App.css';
import { React, useState } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

import Login from "./components/Login";
import Signup from "./components/Signup";
import Feed from "./components/User/Feed";
import UserProfile from "./components/User/UserProfile";

const axios = require("axios");

function App() {
  const [isAuth, setAuth] = useState(false);

  const checkAuthHome = () => { 
    axios.post("http://localhost:5000/api/checkauth", {}, { withCredentials: true })
    .then((response) => {
      setAuth(response.data.status);;
    });
    if (isAuth === true) {
      return (<Feed />);
    } else {
      return (<Login />);
    }
  }

  return (
    <div className="App">
      <Router>
        <Routes>
          <Route exact path="/" element={checkAuthHome()}/>
          <Route exact path="/signup" element={<Signup />}/>
          <Route exact path="/users/:id" element={<UserProfile />}/>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

CodePudding user response:

You must not do data fetching in component render. Try to use useEffect:

function App() {
  const [isAuth, setAuth] = useState(false);

  useEffect(()=>{
    axios.post("http://localhost:5000/api/checkauth", {}, { withCredentials: true })
      .then((response) => {
        setAuth(response.data.status);;
      });
  }, [])

  const checkAuthHome = () => { 
    if (isAuth === true) {
      return (<Feed />);
    } else {
      return (<Login />);
    }
  }

  return (
    <div className="App">
      <Router>
        <Routes>
          <Route exact path="/" element={checkAuthHome()}/>
          <Route exact path="/signup" element={<Signup />}/>
          <Route exact path="/users/:id" element={<UserProfile />}/>
        </Routes>
      </Router>
    </div>
  );
}
  •  Tags:  
  • Related