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

Deactivate numerous buttons with the help of jQuery

Within my MVC view, I have a Razor foreach loop that generates table rows with buttons: @foreach (var item in Model) { <tr> <td>@item.Id</td> <td> <button id="btn" class="button btn-primary" type= ...

Steps to retrieve a value from a promise function

My current challenge involves a function that verifies whether a device is online. Take a look at the code snippet below. const ping = require('ping'); export function checkDeviceStatus(device) { try { const hosts = [device]; let resul ...

Tips for adding and deleting elements after cloning in jQuery

I'm trying to achieve a layout similar to the one shown in this picture. It should display a delete button for each item and an add button to add more items. Check out the example here. I have managed to display the buttons individually, but I'm ...

How do I extract a parameter when passing it to a promise in NodeJS?

Let me simplify this query. I need to fetch a parameter used in a promise. Here's the gist of the code: function foo(param) { return fromPromise(blabla, blabla2, param) .then((res) => { return res }).catch((error) => { console.log( ...

Leveraging jQuery to implement onclick functionality within a Jinja2 loop

I'm currently working with Python, Flask, and Jinja2. When using a for loop, I want to be able to click on the {{ place.place_photo }} element to toggle its details. Initially, I had it functioning correctly but ran into an issue where clicking on on ...

Converting an object to JSON in javascript: A step-by-step guide

I have been attempting to convert my object person into a JSON format. const person = new Object(); person.firstName = 'testFirstName'; person.lastName = 'testLastName'; var myJson = JSON.stringify(person); ...

The AngularJS HTTP interceptor is a crucial component for handling

Is there a way to use an interceptor in AngularJS to log "finished AJAX request" when any request is completed? I've been exploring interceptors and currently have the following setup, but it triggers at the beginning of the request rather than the e ...

What is the best way to properly redirect a page using a router link in Vue.js 2?

I've encountered an issue with the router-link component in Vue.js 2. I have set up my router file index.js import Vue from 'vue'; import VueRouter from 'vue-router'; import HomeView from '../views/HomeView.vue'; import ...

Experimenting with a function invoked from a jQuery AJAX callback using Jasmine testing framework

Currently, I'm working on a function that utilizes an AJAX call to interact with a service. My main goal is to ensure the displayError function is triggered in case of a failure. The ajaxCall function is set up to accept a URL parameter. When the req ...

Error While Installing Atom Editor Packages

Encountering an issue while installing packages in Atom npm ERR! Windows_NT 6.2.9200 npm ERR! argv "C:\\Users\\Jarvis\\AppData\\Local\\atom\\app-1.5.3\\resources\\app&bsol ...

React Checkbox malfunctioning: Troubleshooting and solutions

I have thoroughly researched for a solution to my issue before resorting to posting this question. Unfortunately, none of the answers I found seemed to resolve my problem. Despite trying various methods such as changing, clicking, and checking, my checkbo ...

Is there a way to exclude a specific div based on two select choices?

Check out my Fiddle demonstration here $('select#classes').on('change', function() { var selectedClass = $(this).val(); $('.col-sm-6:not(:contains(' + selectedClass + '))').hide(); $('select#subjec ...

What is the best approach to developing Vue components with unique templates while maintaining the same functionality without duplicating code?

I am working on a project to develop a custom and versatile datatable component. My goal is to be able to adjust the appearance of the datatable on each page, while maintaining consistent functionality. I want to pass data rows into the component and have ...

Encountered an error with "Unexpected token import" while attempting to run pm2 on my React application deployed on a Digital

As I attempt to deploy my application on DigitalOcean and run it with pm2, I encounter the following error: /home/bcavenagh/social/src/index.js:1 (function (exports, require, module, __filename, __dirname) { import React from 'react'; ...

What is the best way to display an HTML page in the bottom right corner instead of within a div?

I am trying to display the content of an HTML page in the bottom right corner of another page using my JavaScript script. However, I do not want to insert a div into the page and then load the content inside it. Instead, I am looking for an alternative way ...

Differences between const and let when utilizing the require function

With io.js now offering ES6 support, you can finally take advantage of the powerful const and let keywords. While let is seen as the successor to var with added capabilities, what about const? We all know what "constant" means, but when is it best practice ...

Issue with Angular Route Guard - Incorrect redirection to login page

I'm encountering an issue with my Angular app where even after the JWT token has expired, I am still able to navigate within the application without any API data being accessible. I've double-checked my setup and it seems right, but for some reas ...

What is the best method for converting a variable with HTML content into a printable string?

In an attempt to display user-entered data from a text box to an HTML div, there seems to be an issue when the data contains HTML content. Instead of displaying the content as a string, it shows it as HTML elements. For example: let text = "<h1>Worl ...

Encountering the error message "'node' is not recognized as an internal or external command" while attempting to install phantomjs via npm

Recently, I've been working on a significant project where I utilized NPM to handle my dependencies. Everything was running smoothly until the team made some changes that required me to update the dependencies and rebuild the project. However, when I ...

Guide to decoding JSONP data sent from a remote server

Working on retrieving data using JSONP. After observing the returned data in Firebug, I can confirm that it is being returned correctly. However, I am facing a challenge in figuring out how to parse it. Is the data returning as a nested array? The callback ...