I have an ionic react app in which I want to show data from a database when the application opens, however the values are only displayed after I navigate to another tab then back to the original one. I will be adding to the database and want the most up to date values to show every time the user navigates to that tab.
I've tried useIonViewWillEnter and useEffect and neither are working the way I want them to.
Is there any way that I can get the values to display upon opening the application then update and display new values every time I navigate to that tab?
This is the page I am trying to render:
const Tab1: React.FC = () => {
const [loans, setLoans] = useState<Loan[]>()
useEffect(() => {
setLoans(getAllLoans())
console.log(loans)
}, []);
return (
<IonPage>
<IonHeader>
<IonToolbar color="primary">
<IonTitle>Select A Loan</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding">
<IonList>
{loans && loans.map((loan) => <IonItem><IonText>{loan.name} {loan.principle} {loan.interest}</IonText></IonItem>)}
</IonList>
</IonContent>
</IonPage>
);
};
And this is the function I am getting the data from. It returns the array of loans that I want to display:
export const getAllLoans = (): Loan[] => {
const loans: Loan[] = []
try {
SQLite.create({
name: 'loan.db', location: 'default'
}).then(async (db: SQLiteObject) => {
try {
const create = await db.executeSql("create table if not exists loans(name VARCHAR(32) NOT NULL, principle REAL NOT NULL, interest REAL NOT NULL)", [])
const query = "SELECT * FROM loans"
const get = db.executeSql(query, []).then(data => {
for(let i=0; i < data.rows.length; i++){
loans.push({
name: data.rows.item(i).name,
principle: data.rows.item(i).principle,
interest: data.rows.item(i).interest
})
}
console.log(loans)
return loans;
});
//console.log('found: '+ loans);
return loans
} catch (e) {
console.log('SQL get error: ', e);
return loans
}
})
} catch(e) {
console.log('database get error ', e)
return loans
}
return loans
}