I have below code. I am accessing /profile page. In the process /profile is accessed by 6 times. It sends 6 times POST request to back end. After using hook useEffect, I see still it access the /profile page 6 times, however now it sends POST request two times to backend.
Is this behaviour normal? Whats wrong here?
import react, {useState, useEffect} from 'react';
import axios from 'axios';
const Profile = () => {
const [firstName, setFirstName] = useState(null);
const [lastName, setLastName] = useState(null);
let user = localStorage.getItem('user');
console.log('Local storage user = ' + user);
const data = {user: user};
const headers = {'Content-Type': 'application/json'};
useEffect ( () => {
try {
axios
.post('/profile', data, {headers: headers})
.then(function (res) {
console.log("Got 200 for /profile request");
let obj = JSON.parse(res.data);
setFirstName(obj.firstname);
setLastName(obj.lastname);
})
}catch (err) {
console.log("Error:" + err.message);
};
}, []);
return (
<div className="medium-text">
<div className="center">
<h2>User profile data</h2>
{firstName && <div>First name: {firstName}</div>}
{lastName && <div>Last name: {lastName}</div>}
</div>
</div>
);
}
export default Profile;
3
Answers
logic is wrong, maybe you can do like this
You need to make sure reactStrictMode is enabled
If I got you right, the current code runs useEffect two times?
Is reactStrictMode enabled? If so, everything will render two times on the dev server (not on prod). This would be the normal behavior.
See My React Component is rendering twice because of Strict Mode