Which is more efficient: Storing the database as a private member variable in Ionic 3 SQLite or creating a new database for every query

Here's a question for you - in the context of Ionic 3, what would be the preferable approach: keeping the opened database as a private member variable within a database provider class, or calling create every time a query is made to the database?

For example...

private db: SQLiteObject;

constructor() {
  this.sqlite.create(...)
    .then((db: SQLiteObject) => {
      this.db = db;
    })
}

queryMethod() {
  db.executeSql(sql, {});
}

...or perhaps like this?

constructor() {

}

queryMethod() {
  this.sqlite.create(...)
    .then((db: SQLiteObject) => {
      db.executeSql(sql, {});
    });
}

I do recognize a potential issue with the first approach, as there is a chance that the database might not have been created prior to being accessed.

Answer №1

A special requirement must be fulfilled when dealing with a Promise, which involves opting for the 2nd choice all the time. By doing so, potential issues can be avoided. Essentially, you should only execute the query after ensuring that the promise has been resolved.

Always adhere to the following pattern:

queryMethod() {
  this.sqlite.create(...)
  .then((db: SQLiteObject) => {
    db.executeSql(sql, {});
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is importing all models into every component considered poor practice?

At my workplace, there is a practice in the legacy code where every single model is imported into all components, regardless of whether they are needed or not. For example: import * as models from '../../view-models/models' ....... let parrot: m ...

The IDE is showing an error, but Jest is able to run it flawlessly

I recently created a Jest unit test for a TypeScript function called checkEmail, which internally uses showAlert. The showAlert function in the utils.ts file looks like this: export const showAlert = (message: string) => { toast(message); }; In my ...

Tips for converting mat-paginator in Angular 4?

Can you provide any suggestions on how to translate the phrase "Items per page" within the Angular mat-paginator tag, which is a component of Material Design? ...

Issue: unable to establish a connection to server at localhost port 5000 while using Next.js getServerSideProps function

I am experiencing an issue with connecting to an API on localhost:5000. The API works perfectly when called from Postman or the browser, but it does not work when called inside Next.js getserverside props: mport { useEffect,useState } from "react"; i ...

The configuration of the property has not been declared (Error: <spyOnProperty>)

Imagine having a MenuComponent @Component({ selector: 'cg-menu', templateUrl: './menu.component.html', styleUrls: [ './menu.component.scss' ] }) export class MenuComponent implements OnInit { menu: MenuItem[]; isLog ...

Angular6 HttpClient: Unable to Inject Headers in Get Request for Chrome and IE11

Under my Angular 6 application, I am attempting to make a GET request while injecting some custom Headers: Here is how my service is structured: @Injectable() export class MyService { constructor(public httpClient: HttpClient) { } getUserInfos(login): Ob ...

Validation of object with incorrect child fields using Typeguard

This code snippet validates the 'Discharge' object by checking if it contains the correct children fields. interface DischargeEntry { date: string; criteria: string; } const isDischargeEntry = (discharge:unknown): discharge is DischargeEntry ...

Angular is not rendering styles correctly

Having two DOMs as depicted in the figures, I'm facing an issue where the circled <div class=panel-heading largeText"> in the first template receives a style of [_ngcontent-c1], while that same <div> gets the style of panel-primary > .pane ...

Content from PHP's unlink() function continues to persistently display

I run an Angular front end along with a PHP back end for my website. I utilize PHP's unlink function to remove specific images from Angular's assets folder: $fileToDelete = "../src/assets/images/".$name; unlink($fileToDelete) or die("Error delet ...

The modifications to the URL made by react-router-dom's 'useSearchParams' do not persist when adjusted through the onChange callback of the mui 'Tabs' component

One feature I am looking to implement is a tab navigation component that changes based on a specific search parameter called tab. For instance, if my URL reads as example.com?tab=test2, I want the navigation bar to highlight the item labeled test2. To ac ...

What is the proper way to enhance properties?

In the process of developing a Vue3 app using Typescript, one of the components is designed to receive data through props. Initially, everything functioned smoothly with the basic setup: props: { when: String, data: Object }, However, I de ...

include choices to .vue document

When looking at Vue documentation, you may come across code like this: var vm = new Vue({ el: '#example', data: { message: 'Hello' }, template: `<div> {{ message }} </div>`, methods: { reverseM ...

Inquiring about the application of spread argument in TypeScript

Here is some code I'm working on: import _ from 'lodash'; function test(num1: number, num2: number) { console.log(num1, num2); } test(..._.take(_.shuffle([0, 1, 2]), 2)); I encountered a TS2556 error while using the TS playground and ...

Securing Angular 2 routes with Auth Guard through canActivate

I've been searching for a solution to this problem for the past 4 hours with no luck. I have multiple Authguards set up, and I want to instruct the router to grant permission if any of them are true, rather than requiring all guards to be true. Curre ...

Different parameters in an Angular filter pipe

Currently, I am facing a challenge in implementing multiple filters on a pipe for a search result page that retrieves data from an API. How can I integrate different parameters into this filter pipe successfully? Access the application here: https://stack ...

Tips for concealing query parameters that are empty or undefined in Angular 2

I'm currently working with Angular2 (RC2) and the new Router (Alpha.8). Is there a way to prevent a query parameter from being displayed in the URL if it is undefined? For example: this.router.navigate(["/results", this.month, this.day], { ...

Trigger a function upon a user's departure from a page or route in Angular 2

Is there a way to trigger a function only when the current route changes away from a specific component, such as when navigating away from "..../user/user-details"? I want this method to execute regardless of whether the route is changed through user inter ...

"Exploring data trends with an ng2-charts line graph displaying x and y axis values

I am attempting to showcase a function using ng2-charts, with a specific set of x and y values. However, the display is currently not showing my values correctly. Here is an example dataset: chartDataSet: ChartDataSets[] = [ { data: [ { x: 5, y: 7 }, ...

Optimal Method for Inserting Lengthy Data using Sequelize

I have a table containing 20 elements. Is there a more concise way to input data into Sequelize without listing each element individually like this: Sequelize.create({ elem1: req.body.eleme1, elem2: req.body.eleme2, elem3: req.body.eleme3, elem4: ...

I am unable to utilize the Web Share API for sharing a file within my React app written in TypeScript

Trying to launch a WebApp for sharing files has been quite a challenge. After some thorough research, I stumbled upon the Web Share API which seemed like the perfect solution based on standard practices. The documentation provided a clear outline of how it ...