0

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.

Papp Zoltán
  • 131
  • 7
  • I removed the StrictMode from App.tsx, but not helped for me. Thank you! – Papp Zoltán Apr 18 '23 at 16:30
  • Please do not add random text to your post to get around the quality filter message: “It looks like your post is mostly code; please add some more details”. Instead, improve your question by including meaningful information about the issue or issues facing your implementation. See [ask] for more information – jmoerdyk Apr 18 '23 at 16:52

3 Answers3

0

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

React.memo (which is a higher-order component)

If you want the useEffect to run once when component is being rendered , try something like this :

change

export default UserInfo;

to

export default React.memo(UserInfo);
ksd030687d
  • 298
  • 2
  • 12
0

It happening due to react in strict mode in v18 you can use below statement if you want to fetch once

if (!userInfo) {
  const data = /*  api call */
  setUserInfo(data);
}

reusable state link

pramod singh
  • 503
  • 2
  • 11
0

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

<React.StrictMode>
</React.StrictMode>

from your App component

Carneiro
  • 167
  • 1
  • 5
  • 1
    This is helped for me. I need remove StrictMode in index.tsx not in App.tsx – Papp Zoltán Apr 18 '23 at 17:06
  • 1
    [Strict Mode](https://react.dev/reference/react/StrictMode) " lets you find common bugs in your components early during development." While you *can* turn if off, this can lead to not quickly finding issues it may help with. – crashmstr Apr 18 '23 at 17:39