'(Firebase| React-query) useDatabaseSnapshot does not update on change of database
I am using useDatabaseSnapshot to get snapshot of database and with subscribe set to true I expect the hook to run again when data changes and re render the component and i am passing data to the child so it should also be re rendered but this behaviour is not happening. Can anyone explain why?
const currentUserSnapshot = useDatabaseSnapshot(["user",user.data?.uid], dbRef, {
subscribe: true,
});
return(
<Home onTransferAmount={onTransferAmount}
onRequestLoan={onRequestLoan}
onLoanPayment={onLoanPayment}
onLogout={onLogout}
isLoanPending={isLoanPending}
movements={currentUserSnapshot.data?.val().movements}
balance={currentUserSnapshot.data?.val().balance}
monthlyPay={currentUserSnapshot.data?.val().monthlyPay}/>
)
Since this was not working I tried another way and that was to use useEffect which takes as dependencies the currentUserSnapshot.data?.val() values
const currentUserSnapshot = useDatabaseSnapshot(["user",user.data?.uid], dbRef, {
subscribe: true,
});
const [balance,setBalance]=useState();
const [movements,setMovements]=useState([]);
const [monthlyPay,setMonthlyPay]=useState();
const [operationDone,setOperationDone]=useState(false);
const [isLoanPending,setIsLoanPending]=useState(false);
useEffect(()=>{
console.log(currentUserSnapshot.data?.val().balance+'changed?')
setBalance(currentUserSnapshot.data?.val().balance);
setMovements(currentUserSnapshot.data?.val().movements);
setMonthlyPay(currentUserSnapshot.data?.val().monthlyPayment);
currentUserSnapshot.data?.val().installments>0 && setIsLoanPending(()=>false);
},[currentUserSnapshot.data?.val().balance,currentUserSnapshot.data?.val().movement,currentUserSnapshot.data?.val().installments,currentUserSnapshot.data?.val().monthlyPayment])
return(
<Home onTransferAmount={onTransferAmount}
onRequestLoan={onRequestLoan}
onLoanPayment={onLoanPayment}
onLogout={onLogout}
isLoanPending={isLoanPending}
movements={movements}
balance={balance}
monthlyPay={monthlyPay}/>
)
This is working sometimes and sometimes not. Does the useDatabaseSnapshot() not update on each change? Please can someone help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
