Hello guys so i have this problem ,when i press a button a function is called and and sends an axios request so i can get some data of my books.When i recieve the data i set with useState a variable.
The problem is that useEffect is triggering without this variable been set and cacthes the try - catch so the Alert message is displaying before i even press the button.For fact its displaying in Home page when i enter the app.
The code is below :
The request
function boughtRentChecker(){
//Checking if the book is Bought
axios.post('http://*********/getBooksBought',
{
userID : global.id,
bookID : bookShow.id
}).then((response) => {
const data = response.data;
console.log(data)
setBookIsBought(data);
})
useEffect(() => {
try{
if(bookIsBought[0].bookBought == 1){
navigation.navigate('WebViewPdf',{paramKey:bookShow})
}
else{
Alert.alert("Book is not Bought")
}
}catch(error){
console.log(error);
}
},[bookIsBought])
CodePudding user response:
useEffect
will run on component mount, regardless of the useEffect dependency (see more here), so you should have a variable to determine if its the first mount:
const componentMounted = useRef(false);
useEffect(() => {
if(!componentMounted.current){
componentMounted.current = true;
// hopefully you dont need a cleanup function
return
}
try{
if(bookIsBought[0].bookBought == 1){
navigation.navigate('WebViewPdf',{paramKey:bookShow})
}
else{
Alert.alert("Book is not Bought")
}
}catch(error){
console.log(error);
}
},[bookIsBought])
Or you could initialize bookIsBought
to some default value (perhaps null or an empty object) and check that bookIsBought isnt that defaultValue:
useEffect(() => {
try{
if(Object.keys(bookIsBought || {}).length > 0 &&
bookIsBought[0].bookBought == 1){
navigation.navigate('WebViewPdf',{paramKey:bookShow})
}
else{
Alert.alert("Book is not Bought")
}
}catch(error){
console.log(error);
}
},[bookIsBought]
CodePudding user response:
To answer your question useEffect
will run on every render. The execution of inside logic is dependent on the dependency array. You can restrict the useEffect
by any bounded condition or with a dependency array to not execute the inside logic on a certain render.
One suggestion, you are using try...catch
block directly inside a useEffect
here. This will not bring you any desired outcome of try...catch. You can try moving the whole try...catch
logic inside some function and call that function inside the useEffect
.