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.
3
Answers
The fetch might be called twice as the component is rendered twice . if you are rendering the component inside another component that is being re-rendered, such as a parent component that updates its state.
you could try to use
If you want the useEffect to run once when component is being rendered , try something like this :
change
to
It happening due to react in strict mode in v18
you can use below statement if you want to fetch once
reusable state link
In development, when strict mode is enabled, components mount twice, so the useEffect hook runs twice. It shouldn’t happen in production.
https://upmostly.com/tutorials/why-is-my-useeffect-hook-running-twice-in-react
You can disable strict mode by removing
from your
App
component