In react funtional component -
useEffect(() => {
if (!referralUserSaved && referralCode && !Object.keys(user).length) {
if (referralCode.trim().length == 4) {
saveReferralsInstalls();
}
}
}, [deviceInfo, referralCode, broadcastSubscribed, androidId, ipAddress]);
Api call where global state is saved to prevent duplcate call
Api.post(`/tableName`, params).send((res) => {
if (res.type !== "error") {
setState({ referralUserSaved: true });
}
});
I understand multiple parameters in useffect causes it to run multiple times but even after the if condition why is the api method called and duplicate data gets stored 2-3 times? The
if(!referralUserSaved)
part should have prevented the duplicate calls
CodePudding user response:
Your parameters are probably reloading before your asynchronous function response.
Remove useless parameters or use a state guard to prevent duplicate reload.
const [fetching, setFetching] = useState(false);
const saveReferralsInstalls = async () => {
setFetching(true);
// Your code
}
useEffect(() => {
if (!fetching && !referralUserSaved && referralCode && !Object.keys(user).length) {
if (referralCode.trim().length == 4) {
saveReferralsInstalls().then(() => setFetching(false));
}
}
}, [deviceInfo, referralCode, broadcastSubscribed, androidId, ipAddress]);