I'm using rxdb to store my data and would like to use databaseController.ts which creates the database object and export query methods which the React components can use. To achieve that I must assure that the database object has been created before anything else. Because right now I get the error TypeError: Cannot read properties of undefined (reading 'contracts') if I try to use getAllNewContractsQuery(). How can I make sure that my database object is available?
databaseController.ts
/* omitted imports etc. */
let db;
export async function initDB() {
await createDatabase();
await db.addCollections({
contracts: {
schema: contractsSchema,
methods: contractDocMethods,
statics: contractsCollectionMethods,
},
});
return db;
}
async function createDatabase() {
db = await createRxDatabase<DatabaseCollections>({
name: 'contractsdb',
storage: getRxStoragePouch('idb'),
multiInstance: true,
ignoreDuplicate: false
});
}
export async function getAllNewContractsQuery() {
const query = await db.contracts.find().where('customerName').eq('Luke Cage')
console.log(await query.exec())
}
export { db }
App.tsx
/* omitted imports etc. */
export default function App() {
useEffect(() => {
const initDBEffect = async () => {
await initDB()
}
initDBEffect()
}, [])
return (
<Provider store={store}>
<Router>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<ContractManager />} />
</Route>
</Routes>
</Router>
</Provider>
);
}
contractManager.tsx
const ContractManager = () => {
useEffect(() => {
const newContracts = async () => {
await getAllNewContractsQuery()
}
newContracts()
}, [])
/* omitted code */
}