skip to Main Content

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

3

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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 .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search