how to pass parameter value in useEffect by function

Viewed 26

Hope you all are doing well, I would like to get data from my API by post method but useEffect is not acceptable in any parameter so I am trying to pass data in a function and call that data in useEffect but the parameter value is not receiving in my function

Here is the code of Result.jsx

const { state } = useLocation();
  const [myProfile, setMyProfile] = useState({ mail: state });
  console.log(myProfile);
  console.log(state);
  const myProfileFun = async () => {
    console.log(myProfile);
    const data = await axios.post(
      "http://localhost:8080/user/searchuser",
      myProfile
    );
    console.log();
    return data;
  };
  useEffect(() => {
    myProfileFun().then((res) => {
      const finaldata = res.data;
      console.log(finaldata);
      setMyProfile(finaldata);
    });
  });

I have to pass data like that

{
   "mail": "xyz@gmail.com"
}

here is the console, if you see it is not consoling inside the myProfileFun

enter image description here

1 Answers

You can add myProfile to the useEffect dependency and check if value is available before function call, so something like this:

useEffect(() => {
  if (myProfile) {
    myProfileFun().then((res) => {
      const finaldata = res.data;
      setMyProfile(finaldata);
    });
  }
},[myProfile]);
Related