skip to Main Content

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


  1. logic is wrong, maybe you can do like this

    import react, {useState, useEffect} from 'react';
    import axios from 'axios';
    
    const Profile = () => {
        const [firstName, setFirstName] = useState(null);
        const [lastName, setLastName] = useState(null);
    
        async fetchProfile() {
           const user = localStorage.getItem('user')
           await axios.post('/profile', {user}, {
               headers: {
                 'Content-Type': 'application/json'
               }
           }).then(function (res) {
              console.log("Got 200 for /profile request");
              let obj = JSON.parse(res.data);
              setFirstName(obj.firstname);
              setLastName(obj.lastname);
            })
        }
    
        useEffect ( () => {
           fetchProfile()
        }, []);
        
        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;
    
    Login or Signup to reply.
  2. You need to make sure reactStrictMode is enabled

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

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