I write a React code, but it call fetch twice when I load page to browser. My question is why? How can I reduce to one call?
The code is the following:
import { useEffect, useState } from "react";
import { useCookies } from "react-cookie";
const UserInfo = () => {
const [cookies, setCookie, removeCookie] = useCookies(['x-auth-token']);
const [userInfo, setUserInfo] = useState({ _id: 0, name: '', email: '', password: '' });
useEffect(() => {
fetch(`http://localhost:8080/api/users/me`, {
method: 'GET',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'x-auth-token': cookies["x-auth-token"],
},
cache: 'no-cache'
}).then((response) => response.json()).then(data => {
console.log(JSON.stringify(data));
setUserInfo(data);
}).catch((e) => {
console.log(e);
});
}, []);
return (
<div className="App">
<h1>Home</h1>
<p>Hello {userInfo.name} from {userInfo.email}!</p>
</div>
);
}
export default UserInfo;
The App.tsx is here:
import "primereact/resources/themes/lara-light-indigo/theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";
import "primeflex/primeflex.css";
import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Register from './pages/register';
import Login from './pages/login';
import Home from './pages/home';
import UserInfo from "./pages/userinfo";
function App() {
return (
<React.StrictMode>
<div className="App">
<BrowserRouter>
<Routes>
<Route path='/register' element={<Register />} />
<Route path="/login" element={<Login />} />
<Route path="/user" element={<UserInfo />} />
<Route path="/" element={<Home />} />
</Routes>
</BrowserRouter>
</div>
</React.StrictMode>
);
}
export default App;
I think my question is not enought length, because I get comment about it is mostly code then question. So I write some words here. Please help me. Writesonic can't tell the true.