'how to pass parameter value in useEffect by function
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": "[email protected]"
}
here is the console, if you see it is not consoling inside the myProfileFun
Solution 1:[1]
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]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fmsthird |
