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
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
3
Answers
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
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 inindex.js
file by removing<React.StrictMode>
This strict mode is only works in
development not in build production
, so i would suggest not to remove the strictModeyou 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 .