skip to Main Content

Below useEffect gets executed before props value is received from parent compoment. I have noticed that this error happens only once after loading a new app and on reloading same app after getting this error , it works and received value from props.
i would highly appreicate for any suggestion to allow below useEffect to run once props value is received.

function Home(props) {
  useEffect(() => {
    axios
      .post("https://........", {
        auth: {
          username: props.username,
          password: props.password,
        },
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  }, [props.username,props.password]);
}

2

Answers


  1. You can simply return to omit that specific execution of the useEffect in case props aren’t defined yet:

    function Home(props) {
      useEffect(() => {
    
        if(!props) { return };
    
        axios
          .post("https://........", {
            auth: {
              username: props.username,
              password: props.password,
            },
          })
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
      }, [props.username,props.password]);
    }
    
    Login or Signup to reply.
  2. You can add a conditional check within the useEffect to verify if the values exist before making the API call. Here’s the modification :

     function Home(props) {
      useEffect(() => {
     // Check if both username and password props are available
       if (props.username && props.password) {
        axios
          .post("https://........", {
             auth: {
              username: props.username,
              password: props.password,
            },
          })
          .then(function (response) {
           console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
       }
     }, [props.username, props.password]);
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search