Executing React Fetch API Twice upon loading the page

Double-fetching Issue with React Fetch API on Initial Page Load

import React, { useState, useEffect } from 'react'
    import axios from 'axios';
    import {  Grid, Paper, TextField } from '@mui/material'
    import PersonOutlineIcon from '@mui/icons-material/PersonOutline';
    
    function FormApi() {
    
      //Styling for Mui fields and paper
      const paperStyle = { padding: '50px ', width: 550, margin: '50px auto' }
    
      //Fetching data from the API
      const [userData, setUserData] = useState([{data:null,support:null}]);
      const apiUrl = 'https://reqres.in/api/users/2';
    
        useEffect(()=>{
    
          const fetchData = async () =>{
    
            await axios.get(`${apiUrl}`)
            .then((response) =>{
              setUserData(response.data)
    
            }).catch((error)=>{
                console.log(error)
            })
          }
    
          fetchData();
          }
    
        ,[]);
    
      return (
    
        <Grid container spacing={2} style={paperStyle}>
    
          <Grid align='center' >
            <Paper elevation={20} >
    
              <Grid align='center'>
    
                <h2 style={{padding:'10px' ,background: "#000080", color: 'white' }}> 
       <PersonOutlineIcon large style={{fontSize:'80%'}} />User Details</h2>
    
              </Grid>
              
              <form>
             
              <img style={{width:"20%"}} src={userData.data  ? userData.data.avatar : ''}/>
                <h1 style={{color:'#000080'}}>{userData.data  ? userData.data.first_name : ''} 
       {userData.data  ? userData.data.last_name : ''}</h1>
    
              <Grid container >
                <Grid item xs={6} >
                  <h2 style={{color:'white', background: "purple"}}>Contact Info</h2>
                  <TextField   value={userData.data  ? userData.data.id : ''}   variant="standard" 
         />
                  <TextField  value={userData.data  ? userData.data.email  : ''}   
       variant="standard" />
                </Grid>
    
                <Grid item align='left' xs={6} style={{marginBottom:'40px'}}>
                  <h2 style={{color:'white', background: "purple"}}>Social Link</h2>
                  <TextField  value={userData.support ? userData.support.url : ''}   
       variant="standard" />
                  <TextField  value={userData.support ? userData.support.text : ''}     
      variant="standard" />
                </Grid>
                
              </Grid>
              </form>
            </Paper>
          </Grid>
        </Grid>       
      )
    }

export default FormApi

Answer №1

In the development environment, React may render components twice, causing confusion for developers. One way to prevent this is by commenting out the <React.StrictMode> tag in the index.js file.

This double rendering only occurs during development and StrictMode offers several benefits for developers:

  • Identification of components with unsafe lifecycles
  • Warning about outdated string ref API usage
  • Notification about deprecated findDOMNode usage
  • Detection of unexpected side effects
  • Recognition of legacy context API
  • Ensuring the reusability of state

If the double rendering issue does not impact your regular development work, it is advisable to retain the <React.StrictMode> tag.

For more information, refer to: React StrictMode

Answer №2

React 18 has implemented a new feature to ensure reusable state in development environments when StrictMode is enabled. This behavior may seem unusual, but it should not affect your production Build.

While it can be a bit annoying, there is a workaround available for this issue. You can find more detailed information on how to handle it in this comprehensive answer: React 18, useEffect is getting called two times on mount

Answer №3

If you encounter this issue, remember that you can utilize the useRef hook to handle it efficiently. Don't worry too much about it as it typically only occurs in development mode.

const renderAfterCalled = useRef(false);

useEffect(() => {
    if (!renderAfterCalled.current) {
      // your API call func
    }

    renderAfterCalled.current = true;
}, []);

Instead of removing <React.StrictMode>, consider exploring other solutions to fix the problem. Remember, <React.StrictMode> is a useful tool during development that identifies potential issues and cautions against unsafe practices.

Answer №4

From my understanding, the problem arises from the HTTP client sending two requests: one to the route path "/" and another to "/favicon.ico"

To resolve this issue, you can update your code as follows:

useEffect(()=>{ checkLocation(); //your code ,[]);

Answer №5

upon further review give this a shot

function FormData() {

  //Styling for form fields and paper
  const paperStyle = { padding: '50px ', width: 550, margin: '50px auto' }

  //Fetching data from API
  const [userData, setUserData] = useState([{data:null,support:null}]);
  const apiUrl = 'https://reqres.in/api/users/2';
//debugger

      const fetchData = async () =>{

        await axios.get(`${apiUrl}`)
        .then((response) =>{
          setUserData(response.data)

        }).catch((error)=>{
            console.log(error)
        })
      }

    useEffect(()=>{

      
      fetchData();
      }

    ,[]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Taking out the z-index from the transition code

Is there a way to restructure the code without needing to use z-index for the transition? Without z-index: https://jsfiddle.net/Legcb42d/ .container1 { position: relative; width: 100%; height: 100%; } .container1.slide { height: auto; min-heigh ...

Creating a clone of JSON for use as a template

I am working with a json template that I fill with product data. Here is an example of the json structure: // product template $scope.productAttributes = { "Code": null, 'Attributes': {} }; When a user inputs produ ...

Is there a way to include this function in an array without triggering it right away?

In my coding project, I am working with an array of functions that return jQuery deferred AJAX objects known as phoneAjaxCalls. The main function called newPhone is where multiple calls are being pushed and it requires two arguments. function newPhone(tlc ...

Experiencing issues running 'npm run dev' on a MacBook with M1 chip and Node.js

After successfully installing node and npm, I was able to get the versions showing on my system. It took multiple attempts, but eventually I got it working by running: npm install However, I encountered more issues when trying to run: npm init I had to c ...

The Bootstrap tooltip effectively fades away after displaying text, but it is not positioned correctly above the icon

Having some issues with my tooltip functionality. It seems to display the text on the left side and fades away upon mouseover, but it doesn't show up in a proper tooltip box over the icon as expected. I suspect that there might be a conflict between j ...

What are some strategies for efficiently displaying a large amount of data on a screen using Javascript and HTML without sacrificing performance?

Imagine having a hefty 520 page book with over 6,200 lines of text ranging from 5 to 300 characters each. The challenge lies in efficiently displaying this content on the screen for users to read without causing lag or performance issues. Attempting to re ...

Fixing TypeError in React App: How to Resolve the "Cannot read property 'prototype' of undefined" Issue

I am completely new to JavaScript and I am struggling to understand the error that keeps popping up. After doing some research, it seems like the error could be due to a poorly written function or something along those lines. Here are the classes involved ...

Having trouble retrieving data from MongoDB and rendering it on an HTML page

Creating a Model Named Field.js in Mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/SuperchainV1', { useNewUrlParser: true }); mongoose.set('useNewUrlParser', true); ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

How can Angular hide a global component when a particular route is accessed?

Is it possible to hide a global component in Angular when a specific route is opened? For instance, consider the following code: app.component.html <app-header></app-header> <app-banner></app-banner> <!-- Global Component I w ...

Set the minimum height of a section in jQuery to be equal to the height of

My goal is to dynamically set the minimum height of each section to match the height of the window. Here is my current implementation... HTML <section id="hero"> </section> <section id="services"> </section> <section id="wo ...

"Unfortunately, this package has been tagged as private, and cannot be accessed at this

I am facing a problem while trying to publish my Angular library on npm. An error message stating npm ERR! This package has been marked as private. Remove the 'private' field from the package.json to publish it. However, I do not have any priva ...

Customizing the Class of a jQuery UI ui-autocomplete Combobox Container

Is there a way to customize the ui-autocomplete div by adding a custom class? I have several autocomplete widgets on my webpage, and I need to style their drop-downs differently. Since editing the ui-autocomplete class directly is not an option, I am wor ...

Why would someone opt to utilize process.env.PORT in their code?

Setting the environment variable PORT to a specific value, such as set PORT=5000, provides explicit instructions on which port the program should use. How does this method differ from simply instructing it to use port 3000? ...

Is it necessary to implement clustering for each route in an Express.js application?

Currently, I am utilizing the cluster module to fork my application within my index.js, which serves as the primary file in the root directory of my website. My application consists of numerous routes. Should I incorporate the cluster code to encapsulate a ...

Setting up NextJS on Vercel for website deployment can encounter a common error known as ENOENT Error, which is caused by the absence of a specific file or

Everything works perfectly on my local machine: import fs from 'fs' import path from 'path' export default function createNewDirectory (tokenSignature: string) { const directoryPath = path.join(process.cwd(), 'notes', to ...

Executing secure journey within TypeScript

Just came across an enlightening article on Medium by Gidi Meir Morris titled Utilizing ES6's Proxy for secure Object property access. The concept is intriguing and I decided to implement it in my Typescript project for handling optional nested object ...

The process of inserting data using NextJS Mysql works seamlessly when executed through phpMyAdmin, however, it encounters issues when

My SQL query works perfectly in phpmyadmin, but I'm encountering an issue when making a request from the API. The API uses the MySQL package which was installed using: npm i mysql This is the SQL code that is causing the problem: BEGIN; INSERT INTO A ...

What are the available choices for constructing HTML based on an ajax response?

Are there any alternatives or libraries available for constructing html from an ajax response? Currently, I am taking the json data received, creating the html as a string, and using a jQuery function to insert it into the DOM. However, I believe there mu ...

When utilizing the `useLocation` hook, the location information appears to be missing

When utilizing a HashRouter, and inside a component making use of useLocation, there seems to be an inconsistency between the window.location object and the location object retrieved from useLocation. While writing this, I have observed that there might b ...