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