0

I have sample API request script in App.js, when I'm running in my local system API request hitting twice, please refer the code and let me know what I did wrong. Thanks in advance

enter image description here

import logo from './logo.svg';
import './App.css';

import React, { useEffect, useState } from "react"; 
function App() { 
  const [user, setUser] = useState([]); 
  const fetchData = () => { return fetch("https://jsonplaceholder.typicode.com/users", {method:'GET', headers: {
 'Accept': 'application/json',
 "Content-Type": "application/x-www-form-urlencoded"
 }}) .then((response) => response.json()) .then((data) => setUser(data)); } 
useEffect(() => { fetchData(); },[]) 
  return ( 
    <main> <h1>User List</h1> <ul> {user && user.length > 0 && user.map((userObj, index) => ( <li key={userObj.id}>{userObj.name}</li> ))} </ul> </main> 
  ); 
} 
export default App;

I'm expecting single request hit while loading page

Hacker
  • 17
  • 2
  • When a state in a component changes (in this case it's `user` in `App`) React re-renders the component. As your `fetchData` is a simple function it gets called again. Page re-renders only once as the second time `user` value does not change. Never use basic functions in React, always use `useCallback`. More: https://www.w3schools.com/react/react_usecallback.asp – KiprasT May 25 '23 at 04:40
  • Duplicate of [React Hooks: useEffect() is called twice even if an empty array is used as an argument](https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar). (also note that the comment above ^ is incorrect) – Guy Incognito May 25 '23 at 04:40

3 Answers3

0
calling Ajax request twice in React

Hi, it is just happened at localhost. If you want to fix it at your localhost, you could remove React.StrictMode at your index.js.

If you deploy on somewhere and don’t want to remove React.StrictMode, it will not happens twice of api calling. You could try to deploy on vercel and check it out. That is fine

Yewin
  • 160
  • 1
  • 7
0

In React.Js, The strict Mode is enabled. So, its re-render your whole component twice so you can easily check the result. This is the way that reactjs tell you to double check your API result or other functionality is working properly or not. You can diabled in index.js file by removing <React.StrictMode>

<React.StrictMode>
    <App />
  </React.StrictMode>

This strict mode is only works in development not in build production, so i would suggest not to remove the strictMode

Kannu Mandora
  • 479
  • 2
  • 10
0

you are using useEffect it will render as soon as page load . So in index.js file you'll have <React.StrictMode> remove and try it .