<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.5">Jekyll</generator><link href="https://jepiqueau.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://jepiqueau.github.io/" rel="alternate" type="text/html" /><updated>2024-04-09T18:32:42+00:00</updated><id>https://jepiqueau.github.io/feed.xml</id><title type="html">JeepQ Capacitor Plugins Tutorials</title><subtitle>Tutorials on how to use JeepQ capacitor plugins.</subtitle><author><name>Quéau Jean Pierre</name></author><entry><title type="html">Ionic 7 TypeOrm SQLite Database App Example Tutorial using React and @capacitor-community/sqlite</title><link href="https://jepiqueau.github.io/2024/02/19/Ionic7React-TypeOrm-SQLite-App.html" rel="alternate" type="text/html" title="Ionic 7 TypeOrm SQLite Database App Example Tutorial using React and @capacitor-community/sqlite" /><published>2024-02-19T00:00:00+00:00</published><updated>2024-02-19T00:00:00+00:00</updated><id>https://jepiqueau.github.io/2024/02/19/Ionic7React-TypeOrm-SQLite-App</id><content type="html" xml:base="https://jepiqueau.github.io/2024/02/19/Ionic7React-TypeOrm-SQLite-App.html"><![CDATA[<hr />

<p><em>last updated on February 19, 2024 by Quéau Jean Pierre</em></p>

<p>In that tutorial we will learned how to create a Ionic7/React TypeOrm basic application and implement the @capacitor-community/sqlite plugin to store the data in a SQLite database.</p>

<p>The first part of the tutorial will concentrate on how to create that application and run it on a Web browser where the data will be stored on an Indexed database using sql.js and localForage modules.
Go to <a href="#part-1---web---table-of-contents">Part 1 - Web - Table of Contents</a></p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/SQLite/main/Part-1/typeorm-ionic7-react-sqlite-app">Part-1/typeorm-ionic7-react-sqlite-app</a></p>

<p>Thanks to the Ionic Team and their hard work to bring CAPACITOR 5, the second part will concentrate on native platforms (iOS and Android) and also on Electron platform.</p>

<p>Go to <a href="#part-2---native---table-of-contents">Part 2 - Native - Table of Contents</a></p>

<p>!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!! Work in Progress !!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!</p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/SQLite/Part-2/typeorm-ionic7-react-sqlite-app">Part-2/typeorm-ionic7-react-sqlite-app</a></p>

<h2 id="part-1---web---table-of-contents">Part 1 - Web - Table of Contents</h2>

<hr />
<ul>
  <li><a href="#install-new-ionic-application">Install New Ionic Application</a></li>
  <li><a href="#install-required-packages">Install Required Packages</a></li>
  <li><a href="#create-the-typeorm-directory-structure">Create the Typeorm Directory Structure</a></li>
  <li><a href="#add-code-to-these-files">Add Code to these Files</a>
    <ul>
      <li><a href="#author-database">Author Database</a></li>
      <li><a href="#user-database">User Database</a></li>
      <li><a href="#capacitor-sqlite-connection">Capacitor SQLite Connection</a></li>
      <li><a href="#utilities">Utilities</a></li>
    </ul>
  </li>
  <li><a href="#correcting-a-bug-in-the-typeorm-capacitor-driver">Correcting a Bug in the TypeOrm Capacitor Driver</a></li>
  <li><a href="#update-config-and-packagejson-scripts">Update Config and Package.json Scripts</a></li>
  <li><a href="#generate-the-initial-typeorm-migrations">Generate the Initial TypeOrm Migrations</a></li>
  <li><a href="#implementing-the-application">Implementing the Application</a>
    <ul>
      <li><a href="#maintsx">Main.tsx</a></li>
      <li><a href="#apptsx">App.tsx</a></li>
      <li><a href="#appmenu-component">AppMenu Component</a></li>
      <li><a href="#home-page">Home Page</a></li>
      <li><a href="#applogo-component">AppLogo Component</a></li>
      <li><a href="#appintrotext-component">AppIntroText Component</a></li>
      <li><a href="#appmenu-component">AppMenuButton Component</a></li>
    </ul>
  </li>
  <li><a href="#run-the-web-sqlite-app">Run the Web SQLite App</a></li>
  <li><a href="#generate-a-new-migration-on-author">Generate a New Migration on Author</a>
    <ul>
      <li><a href="#entity-author">Entity Author</a></li>
      <li><a href="#add-a-script-in-packagejson">Add a Script in Package.json</a></li>
      <li><a href="#generate-the-migration-in-typeorm-cli">Generate the Migration in TypeOrm CLI</a></li>
      <li><a href="#add-the-migration-to-the-authordatasource">Add the Migration to the AuthorDataSource</a></li>
      <li><a href="#execute-the-migration-in-the-web-app">Execute the Migration in the Web App</a></li>
    </ul>
  </li>
  <li><a href="#part-1-conclusion">Part 1 Conclusion</a></li>
</ul>

<hr />

<h3 id="install-new-ionic-application">Install New Ionic Application</h3>

<ul>
  <li>
    <p>Install the latest version of Ionic CLI globally installed on your device, run the below command.</p>

    <pre><code class="language-bash"> sudo npm install -g @ionic/cli
 sudo npm install -g npm install g generate-react-cli
</code></pre>
  </li>
  <li>
    <p>Create a new blank Ionic React app</p>

    <pre><code class="language-bash"> ionic start typeorm-ionic7-react-sqlite-app blank --type=react --capacitor
</code></pre>
  </li>
  <li>
    <p>Go inside the project folder</p>

    <pre><code class="language-bash"> cd ./typeorm-ionic7-react-sqlite-app
</code></pre>
  </li>
</ul>

<h3 id="install-required-packages">Install Required Packages</h3>

<ul>
  <li>
    <p>run the below commands</p>

    <pre><code class="language-bash"> npm install --save @capacitor-community/sqlite
 npm install --save reflect-metadata
 npm install --save typeorm
 npm install --save @capacitor/toast
 npm install --save @ionic/pwa-elements
 npm install --save-dev @types/node
 npm install --save-dev ts-node
 npm install --save-dev copyfiles
 npm install --save-dev unplugin-swc
</code></pre>
  </li>
</ul>

<h3 id="create-the-typeorm-directory-structure">Create the Typeorm Directory Structure</h3>

<ul>
  <li>
    <p>With your favorite Editor, create the following directory structure under the src directory:</p>

    <div align="center"><br /><img src="/images/TypeOrmAppDirectoriesTutorial.png" width="300" /></div>
    <p><br /></p>

    <p>The tutorial will utilize two datasources: Author and User.</p>

    <p>In the AuthorDataSource, three entities —Author, Category, and Post— will be defined.</p>

    <p>In the UserDataSource, two entities —User and Item— will be utilized.</p>
  </li>
  <li>
    <p>Create two additional files under the <code>databases</code> directory:</p>

    <ul>
      <li>
        <p><code>sqliteParams.ts</code> This file will handle the connection to the <code>@capacitor-community/sqlite</code> plugin.</p>
      </li>
      <li>
        <p><code>utilities.ts</code> This file will contain various utility methods.</p>
      </li>
    </ul>

    <p>These files will provide essential functionalities and configurations for working with the SQLite plugin and implementing utility functions.</p>
  </li>
</ul>

<h3 id="add-code-to-these-files">Add Code to these Files</h3>

<ul>
  <li>add <code>import "reflect-metadata";</code> in the main file of your App.</li>
</ul>

<h4 id="author-database">Author Database</h4>

<ul>
  <li><code>AuthorDataSource.ts</code></li>
</ul>

<pre><code class="language-ts"> import { DataSource , type DataSourceOptions} from 'typeorm';
 import sqliteParams from '../sqliteParams';
 import * as entities from '../entities/author';
 import * as migrations from '../migrations/author';

 // Author Database Name
 const dbName = "react-sqlite-author"

 const dataSourceConfig: DataSourceOptions = {
  name: 'authorConnection',
  type: 'capacitor',
  driver: sqliteParams.connection,
  database: dbName,
  mode: 'no-encryption',
  entities: entities,
  migrations: migrations, //["../migrations/author/*{.ts,.js}"]
  subscribers: [],
  logging: [/*'query',*/ 'error','schema'],
  synchronize: false,     // !!!You will lose all data in database if set to `true`
  migrationsRun: false
 };
 export const dataSourceAuthor = new DataSource(dataSourceConfig);
 const authorDataSource = {
  dataSource: dataSourceAuthor,
  dbName: dbName
 };

 export default authorDataSource;
</code></pre>

<ul>
  <li><code>UserDataSource.ts</code></li>
</ul>

<pre><code class="language-ts"> import { DataSource , type DataSourceOptions} from 'typeorm';
 import sqliteParams from '../sqliteParams';
 import * as entities from '../entities/user';
 import * as migrations from '../migrations/user';

 // User Database Name
 const dbName = "react-sqlite-user"

 const dataSourceConfig: DataSourceOptions = {
  name: 'userConnection',
  type: 'capacitor',
  driver: sqliteParams.connection,
  database: dbName,
  mode: 'no-encryption',
  entities: entities,
  migrations: migrations, // ["../migrations/user/*.{js,ts}"],
  subscribers: [],
  logging: [/*'query',*/ 'error','schema'],
  synchronize: false,     // !!!You will lose all data in database if set to `true`
  migrationsRun: false
 };
 export const dataSourceUser = new DataSource(dataSourceConfig);
 const userDataSource = {
  dataSource: dataSourceUser,
  dbName: dbName
 };
 export default userDataSource;

</code></pre>

<ul>
  <li>Entity: <code>author.ts</code></li>
</ul>

<pre><code class="language-ts"> import {Entity, PrimaryGeneratedColumn, Column, OneToMany, CreateDateColumn} from 'typeorm';
 import {Post} from './post';

 @Entity('author')
 export class Author {

  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  name!: string;

  @Column({nullable: true})
  company!: string;
  
  @Column({nullable: true})
  birthday!: string;

  @Column({unique: true})
  email!: string;

  @OneToMany(type =&gt; Post, post =&gt; post.author)
  posts!: Post[];
  
 }
</code></pre>

<ul>
  <li>Entity: <code>category.ts</code></li>
</ul>

<pre><code class="language-ts"> import {Entity, PrimaryGeneratedColumn, Column} from 'typeorm';

@Entity('category')
 export class Category {

    @PrimaryGeneratedColumn()
    id!: number;

    @Column({unique: true})
    name!: string;

 } 
</code></pre>

<ul>
  <li>Entity: <code>post.ts</code></li>
</ul>

<pre><code class="language-ts"> import {Entity, Column, PrimaryGeneratedColumn, ManyToOne, ManyToMany,
    JoinTable, type Relation, CreateDateColumn} from 'typeorm';
 import {Author} from './author';
 import {Category} from './category';

 @Entity('post')
 export class Post {
 @PrimaryGeneratedColumn()
 id!: number;

 @Column()
 title!: string;

 @Column('text')
 text!: string;

 @ManyToMany(type =&gt; Category, {
    cascade: ['insert']
 })
 @JoinTable()
 categories!: Category[];

 @ManyToOne(type =&gt; Author, author =&gt; author.posts, {
    cascade: ['insert']
 })
 author!: Relation&lt;Author&gt;;

 }
</code></pre>

<ul>
  <li><code>entities/author/index.ts</code></li>
</ul>

<pre><code class="language-ts"> import { Author } from './author';
 import { Category } from './category';
 import { Post } from './post';

 export { Author, Category, Post };
</code></pre>

<ul>
  <li><code>migrations/author/index.ts</code></li>
</ul>

<pre><code class="language-ts"> export {};
</code></pre>

<h4 id="user-database">User Database</h4>

<ul>
  <li><code>UserDataSource.ts</code></li>
</ul>

<pre><code class="language-ts"> import { DataSource , type DataSourceOptions} from 'typeorm';
 import sqliteParams from '../sqliteParams';
 import * as entities from '../entities/user';
 import * as migrations from '../migrations/user';

 // User Database Name
 const dbName = "react-sqlite-user"

 const dataSourceConfig: DataSourceOptions = {
  name: 'userConnection',
  type: 'capacitor',
  driver: sqliteParams.connection,
  database: dbName,
  mode: 'no-encryption',
  entities: entities,
  migrations: migrations, // ["../migrations/user/*.{js,ts}"],
  subscribers: [],
  logging: [/*'query',*/ 'error','schema'],
  synchronize: false,     // !!!You will lose all data in database if set to `true`
  migrationsRun: false
 };
 export const dataSourceUser = new DataSource(dataSourceConfig);
 const userDataSource = {
  dataSource: dataSourceUser,
  dbName: dbName
 };
 export default userDataSource;
</code></pre>

<ul>
  <li>Entity: <code>item.ts</code></li>
</ul>

<pre><code class="language-ts"> import {Entity, Column, PrimaryGeneratedColumn, ManyToOne,
		type Relation} from 'typeorm';
 import {User} from "./user";

 @Entity('item')
 export class Item {
	@PrimaryGeneratedColumn()
	id!: number;

	@Column()
	name!: string;

	@Column({unique: true})
	phoneNumber!: number;

	@ManyToOne(type =&gt; User, user =&gt; user.items, {
		cascade: ['insert']
	})
	user!: Relation&lt;User&gt;;
  
 }
</code></pre>

<ul>
  <li>Entity: <code>user.ts</code></li>
</ul>

<pre><code class="language-ts"> import {Entity, PrimaryGeneratedColumn, Column, OneToMany} from "typeorm"; 
 import {Item} from "./item";

 @Entity('user') 
 export class User {   

  @PrimaryGeneratedColumn()
  id!: number; 
  
  @Column()
  firstName!: string; 
  
  @Column()
  lastName!: string;

  @Column({unique: true})
  email!: string; 

  @OneToMany(type =&gt; Item, item =&gt; item.user)
  items!: Item[];

 }
</code></pre>

<ul>
  <li><code>entities/user/index.ts</code></li>
</ul>

<pre><code class="language-ts"> import { Item } from './item';
 import { User } from './user';

 export { User, Item };
</code></pre>

<ul>
  <li><code>migrations/user/index.ts</code></li>
</ul>

<pre><code class="language-ts"> export {};
</code></pre>

<h4 id="capacitor-sqlite-connection">Capacitor SQLite Connection</h4>

<ul>
  <li><code>sqliteParams.ts</code></li>
</ul>

<pre><code class="language-ts"> import { Capacitor } from '@capacitor/core';
 import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';
 const sqliteConnection: SQLiteConnection = new SQLiteConnection(CapacitorSQLite);
 const sqlitePlugin = CapacitorSQLite;
 const platform: string = Capacitor.getPlatform();
 const sqliteParams = {
    connection: sqliteConnection,
    plugin: sqlitePlugin,
    platform: platform
 }
  export default sqliteParams;
</code></pre>

<h4 id="utilities">Utilities</h4>

<ul>
  <li><code>utilities.ts</code></li>
</ul>

<pre><code class="language-ts"> import { DataSource } from "typeorm";
 import authorDataSource from './datasources/AuthorDataSource';
 import userDataSource from './datasources/UserDataSource';
 import sqliteParams from './sqliteParams';

 export const initializeDataSources = (async () =&gt; {
    //check sqlite connections consistency
    await sqliteParams.connection.checkConnectionsConsistency()
    .catch((e) =&gt; {
        console.log(e);
        return {};
    });

    // Loop through the DataSources
    for (const mDataSource of [authorDataSource , userDataSource]) {
        // initialize
        await mDataSource.dataSource.initialize();
        if (mDataSource.dataSource.isInitialized) {
        // run the migrations
        await mDataSource.dataSource.runMigrations();
        }
        if( sqliteParams.platform === 'web') {
        await sqliteParams.connection.saveToStore(mDataSource.dbName);
        }                    
    } 
 });

 export const getCountOfElements =  (async (connection: DataSource,  entity:any): Promise&lt;number&gt; =&gt; {
    // Get the repository for your entity
    const repository = connection.getRepository(entity);
    // Use the count() method to query the count of elements in the table
    const count = await repository.count();
  
    return count;
 });
</code></pre>

<h3 id="correcting-a-bug-in-the-typeorm-capacitor-driver">Correcting a Bug in the TypeOrm Capacitor Driver</h3>

<ul>
  <li>
    <p>the bug is referenced “PRAGMA must run under query method in Capacitor sqlite #10687” in the typeorm/issues</p>
  </li>
  <li>
    <p>create a <code>scripts</code> directory at the root of the App.</p>
  </li>
  <li>
    <p>create a <code>modify-typeorm.cjs</code> file under this directory with:</p>
  </li>
</ul>

<pre><code class="language-js">    const fs = require('fs');

    const filePath = './node_modules/typeorm/driver/capacitor/CapacitorQueryRunner.js';
    const lineToModify = 61;
    const replacementText = '    else if (["INSERT", "UPDATE", "DELETE"].indexOf(command) !== -1) {';

    fs.readFile(filePath, 'utf8', (err, data) =&gt; {
        if (err) {
            console.error('Error reading file:', err);
            return;
        }

        // Split data by line
        const lines = data.split('\n');

        // Modify the specific line
        if (lines.length &gt;= lineToModify) {
            lines[lineToModify - 1] = replacementText; // Line numbers are 1-based
        } else {
            console.error('Line number to modify is out of range.');
            return;
        }

        // Join lines back together
        const modifiedData = lines.join('\n');

        // Write the modified data back to the file
        fs.writeFile(filePath, modifiedData, 'utf8', (err) =&gt; {
            if (err) {
                console.error('Error writing file:', err);
                return;
            }
            console.log('File modified successfully.');
        });
    });
</code></pre>

<h3 id="update-config-and-packagejson-scripts">Update Config and Package.json Scripts</h3>

<ul>
  <li>
    <p>For Web application only the appID of the <code>capacitor.config.ts</code> must be amended with <code>YOUR_APP_ID</code></p>
  </li>
  <li>For the <code>package .json</code> file
    <ul>
      <li>
        <p>add the following script below <code>"build": "tsc &amp;&amp; vite build",</code>,</p>

        <pre><code class="language-json">  "copy:sql:wasm": "copyfiles -u 3 node_modules/sql.js/dist/sql-wasm.wasm public/assets",
  "build:web": "npm run copy:sql:wasm &amp;&amp; npm run build",
  "typeorm:migration:generate:initialAuthor": "npx typeorm-ts-node-esm migration:generate src/databases/migrations/author/InitialAuthorPost -d src/databases/datasources/AuthorDataSource.ts",
  "typeorm:migration:generate:initialUser": "npx typeorm-ts-node-esm migration:generate src/databases/migrations/user/InitialUserPost -d src/databases/datasources/UserDataSource.ts",
  "postinstall": "node ./scripts/modify-typeorm.cjs"
</code></pre>
      </li>
      <li>
        <p>modify the <code>"dev": "vite",</code> with</p>

        <pre><code class="language-json">  "dev": "npm run copy:sql:wasm &amp;&amp; vite",
</code></pre>
      </li>
    </ul>
  </li>
  <li>
    <p>Open the <code>tsconfig.node.json</code> file  and add <code>"skipLibCheck": true,</code> in the “compilerOptions”.</p>
  </li>
  <li>
    <p>Open the <code>tsconfig.json</code> file:</p>

    <ul>
      <li>
        <p>modify “target”: “ESNext” with <code>"target": "esnext"</code> in “compilerOptions”</p>
      </li>
      <li>
        <p>add in “compilerOptions”</p>
      </li>
    </ul>

    <pre><code class="language-json">     "strictPropertyInitialization": false, // added
     "experimentalDecorators": true, //For DB ORM decorators
     "emitDecoratorMetadata": true, //For DB ORM decorators
</code></pre>

    <ul>
      <li>before “include” add:</li>
    </ul>

    <pre><code class="language-json">   "ts-node": {
     "esm": true,
     "experimentalSpecifierResolution": "node"
   },
</code></pre>
  </li>
  <li>
    <p>Open the <code>vite.config.ts</code> file  and add</p>

    <ul>
      <li>
        <p><code>import swc from 'unplugin-swc';</code> // Support using decorators without explicitly set <code>types</code> in <code>TypeORM</code></p>
      </li>
      <li>
        <p>in the <code>plugin</code>section</p>
      </li>
    </ul>

    <pre><code class="language-ts"> plugins:[
     ...

     legacy,
     swc.vite({
         exclude: [], //Default would exclude all file from ``node_modules``
         jsc: {
             minify: {
             compress: true,
             mangle: true,
             //Suggested by ``capacitor-sqlite``
             keep_classnames: true,
             keep_fnames: true,
             },
         },
     }),
    
     ...
 ]
</code></pre>
  </li>
</ul>

<h3 id="generate-the-initial-typeorm-migrations">Generate the Initial TypeOrm Migrations</h3>

<ul>
  <li>Execute the following commands:</li>
</ul>

<pre><code class="language-bash"> npm run postinstall
 npm run build
 npm run typeorm:migration:generate:initialAuthor
 npm run typeorm:migration:generate:initialUser
</code></pre>

<ul>
  <li>
    <p>Update the <code>migrations/index.ts</code> files by using the name of the migration’s file created</p>

    <ul>
      <li><code>migrations/author/index.ts</code></li>
    </ul>

    <pre><code class="language-ts"> import {InitialAuthorPost1708269296396} from './1708269296396-InitialAuthorPost';
 export {InitialAuthorPost1708269296396};
</code></pre>

    <ul>
      <li><code>migrations/user/index.ts</code></li>
    </ul>

    <pre><code class="language-ts">import {InitialUserPost1708269424717} from './1708269424717-InitialUserPost';
 export {InitialUserPost1708269424717};
</code></pre>
  </li>
</ul>

<h3 id="implementing-the-application">Implementing the Application</h3>

<p>The setup for TypeORM is almost complete. We still need to initialize the DataSources and execute the migrations. This is implemented in the <code>main.ts</code> file.</p>

<h4 id="maintsx">Main.tsx</h4>

<ul>
  <li>Open the <code>main.tsx</code> file and replace the code with:</li>
</ul>

<pre><code class="language-ts"> import "reflect-metadata";
 import React from 'react';
 import { createRoot } from 'react-dom/client';
 import App from './App';

 import { JeepSqlite } from 'jeep-sqlite/dist/components/jeep-sqlite';
 import { defineCustomElements as pwaElements} from '@ionic/pwa-elements/loader';
 import sqliteParams from './databases/sqliteParams';
 import {initializeDataSources} from './databases/utilities';

 pwaElements(window);
 customElements.define('jeep-sqlite', JeepSqlite);

 const rootRender = async () =&gt; {

  await initializeDataSources();

  const container = document.getElementById('root');
  const root = createRoot(container!);
  root.render(
    &lt;React.StrictMode&gt;
      &lt;App /&gt;
    &lt;/React.StrictMode&gt;
  );
 }
 if (sqliteParams.platform !== "web") {
    rootRender();
 } else {
    window.addEventListener('DOMContentLoaded', async () =&gt; {
      // Create the "jeep-sqlite" web component
      const jeepEl = document.createElement("jeep-sqlite");
      // Set the style for the button
      //to pick or save the database from/to local disk
      jeepEl.buttonOptions = '{"backgroundColor":"#fb2a2a", "top":"70%","fontSize":"1.1em"}';
      document.body.appendChild(jeepEl);
      customElements.whenDefined('jeep-sqlite').then(async () =&gt; {
        await sqliteParams.connection.initWebStore();
        rootRender();
      })
      .catch ((err) =&gt; {
        console.log(`Error: ${err}`);
        throw new Error(`Error: ${err}`)
      });
    });
 }

</code></pre>

<h4 id="apptsx">App.tsx</h4>

<p>The App will feature a menu that allows users to navigate from the Home page to either the Author page or the User page, and then return to the Home page.</p>

<p>The Home page will display a logo and an introduction text using the AppLogo and AppIntroText components, respectively.</p>

<p>The Author page will allow users to create authors, categories, and posts in the database. It will then display them using the PostList component and provide an icon button for saving the database to the local disk.</p>

<p>The User page will enable users to create users and items in the database. Subsequently, it will showcase them using the UserList component and furnish an icon button for saving the database to the local disk.</p>

<ul>
  <li>Open the <code>App.tsx</code> file and make the following changes:</li>
</ul>

<pre><code class="language-ts"> import React from 'react';
 import UsersPage from './pages/UsersPage';
 import AuthorsPage from './pages/AuthorsPage';
 import AppMenu from './components/AppMenu/AppMenu';
</code></pre>

<p>and</p>

<pre><code class="language-ts"> const App: React.FC = () =&gt; {
    return (
        &lt;IonApp&gt;
        &lt;IonReactRouter&gt;
            &lt;AppMenu /&gt;
            &lt;IonRouterOutlet id="main-content"&gt;
            &lt;Route exact path="/home"&gt;
                &lt;Home /&gt;
            &lt;/Route&gt;
            &lt;Route exact path="/"&gt;
                &lt;Redirect to="/home" /&gt;
            &lt;/Route&gt;
            &lt;Route path="/users" component={UsersPage} /&gt;
            &lt;Route path="/authors" component={AuthorsPage} /&gt;
            &lt;/IonRouterOutlet&gt;
        &lt;/IonReactRouter&gt;
        &lt;/IonApp&gt;
    );
 };
</code></pre>

<h4 id="appmenu-component">AppMenu Component</h4>

<pre><code class="language-bash">    npx generate-react-cli component AppMenu 
</code></pre>

<p>Answer to the question to get only the component file and a component.css file and not lazy loaded.</p>

<ul>
  <li>Open the <code>AppMenu.css</code> and copy</li>
</ul>

<pre><code class="language-css"> .AppMenu  {
    .menu-ion-label {
        color:antiquewhite;
        font-size: 1.1rem;
        font-weight: Bold;
        font-style: italic;
    }
    ion-button {
        --background: transparent;
        --color: initial;
        font-size: 0.8rem;
    }
 }
</code></pre>

<ul>
  <li>Open the <code>AppMenu.tsx</code> and replace</li>
</ul>

<pre><code class="language-ts"> import React from 'react';
 import './AppMenu.css';
 import { IonMenu, IonHeader, IonToolbar, IonTitle, IonContent, IonLabel,
         IonList, IonItem, IonButton, IonItemGroup, IonItemDivider} from '@ionic/react';

 interface AppMenuProps {}

 const AppMenu: React.FC&lt;AppMenuProps&gt; = () =&gt; {
  const closeMenu = () =&gt; {
    const menu = document.querySelector('ion-menu');
    menu!.close();
  };
  return (
    &lt;IonMenu className="AppMenu" side="end" contentId="main-content"&gt;
      &lt;IonHeader&gt;
        &lt;IonToolbar&gt;
          &lt;IonTitle&gt;Menu Content&lt;/IonTitle&gt;
        &lt;/IonToolbar&gt;
      &lt;/IonHeader&gt;
      &lt;IonContent&gt;
        &lt;IonList&gt;
          &lt;IonItemGroup&gt;
            &lt;IonItemDivider&gt;
              &lt;IonLabel class="menu-ion-label"&gt;Authors DB&lt;/IonLabel&gt;
            &lt;/IonItemDivider&gt;
            &lt;IonItem onClick={closeMenu}&gt;
              &lt;IonButton size="default" routerLink="/authors" expand="full"&gt;Author's List&lt;/IonButton&gt;
            &lt;/IonItem&gt;
          &lt;/IonItemGroup&gt;
          &lt;IonItemGroup&gt;
            &lt;IonItemDivider&gt;
              &lt;IonLabel class="menu-ion-label"&gt;Users DB&lt;/IonLabel&gt;
            &lt;/IonItemDivider&gt;
            &lt;IonItem onClick={closeMenu}&gt;
              &lt;IonButton size="default" routerLink="/users" expand="full"&gt;User's List&lt;/IonButton&gt;
            &lt;/IonItem&gt;
          &lt;/IonItemGroup&gt;
          {/* ... other menu items */}
        &lt;/IonList&gt;
      &lt;/IonContent&gt;
    &lt;/IonMenu&gt;
  )
 };
 export default AppMenu;
</code></pre>

<h4 id="home-page">Home Page</h4>

<ul>
  <li>Open the Home.tsx file and update the code with</li>
</ul>

<pre><code class="language-ts"> import React from 'react';
 import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/react';
 import AppMenuButton from '../components/AppMenuButton/AppMenuButton';
 import AppLogo from '../components/AppLogo/AppLogo';
 import AppIntroText from '../components/AppIntroText/AppIntroText';

 import './Home.css';

 const Home: React.FC = () =&gt; {
  return (
    &lt;IonPage&gt;
      &lt;IonHeader&gt;
        &lt;IonToolbar&gt;
          &lt;AppMenuButton /&gt;
          &lt;IonTitle&gt;Home&lt;/IonTitle&gt;
        &lt;/IonToolbar&gt;
      &lt;/IonHeader&gt;
      &lt;IonContent fullscreen&gt;
        &lt;IonHeader collapse="condense"&gt;
          &lt;IonToolbar&gt;
            &lt;IonTitle size="large"&gt;Home&lt;/IonTitle&gt;
          &lt;/IonToolbar&gt;
        &lt;/IonHeader&gt;
        &lt;div id="container"&gt;
          &lt;AppLogo /&gt;
          &lt;AppIntroText /&gt;
        &lt;/div&gt;
      &lt;/IonContent&gt;
    &lt;/IonPage&gt;
  );
 };

 export default Home;

</code></pre>

<ul>
  <li>Delete the <code>ExploreContainer.tsx</code> and <code>ExploreContainer.css</code> files under the <code>src/components</code> directory</li>
</ul>

<h4 id="applogo-component">AppLogo Component</h4>

<ul>
  <li>
    <p>Create an <code>AppLogo</code> React component</p>

    <pre><code class="language-bash"> npx generate-react-cli component AppLogo 
</code></pre>
  </li>
  <li>
    <p>In your Editor replace the code of <code>AppLogo/AppLogo.tsx</code> with</p>
  </li>
</ul>

<pre><code class="language-ts"> import React from 'react';
 import './AppLogo.css';

 interface AppLogoProps {}

 const AppLogo: React.FC&lt;AppLogoProps&gt; = () =&gt; (
    &lt;div className="AppLogo"&gt;
        &lt;img src="assets/JeepQLogo.png" width="128" height="128" /&gt;
    &lt;/div&gt;
 );

 export default AppLogo
</code></pre>
<p>Obviously use your own logo and store it in the <code>public/assets</code> folder.</p>

<ul>
  <li>In your Editor replace the code of <code>AppLogo/AppLogo.css</code> with</li>
</ul>

<pre><code class="language-css"> .AppLogo {
    width: 100%;
    max-height: 200px;
    display: flex;
    justify-content: center;
 }
</code></pre>

<h4 id="appintrotext-component">AppIntroText Component</h4>

<ul>
  <li>
    <p>Create an <code>AppIntroText</code> React component</p>

    <pre><code class="language-bash"> npx generate-react-cli component AppIntroText 
</code></pre>
  </li>
  <li>
    <p>In your Editor replace the code of <code>AppIntroText/AppIntroText.tsx</code> with</p>
  </li>
</ul>

<pre><code class="language-ts"> import React from 'react';
 import './AppIntroText.css';

 interface AppIntroTextProps {}

 const AppIntroText: React.FC&lt;AppIntroTextProps&gt; = () =&gt; (
  &lt;div className="AppIntroText"&gt;
    &lt;div id="app-intro-header"&gt;
      &lt;h3&gt;
        Welcome to the Ionic7/React/Vite TypeOrm SQLite Database App Example Tutorial
      &lt;/h3&gt;
      &lt;h4&gt;using @capacitor-community/sqlite&lt;/h4&gt;
    &lt;/div&gt;
    &lt;div id="app-intro-content"&gt;
      &lt;p&gt;The purpose is to demonstrate the basic setup of the App. &lt;/p&gt;
      &lt;p&gt;The CRUD methods could be implemented from there&lt;/p&gt;
    &lt;/div&gt;
  &lt;/div&gt;
 );

 export default AppIntroText;
</code></pre>

<p>Fill free to put whatever text you would like to see</p>

<ul>
  <li>In your Editor replace the code of <code>AppIntroText/AppIntroText.css</code> with</li>
</ul>

<pre><code class="language-css"> .AppIntroText {
    display: flex;
    flex-direction: column;
 }
 #app-intro-header {
    margin-top: 10%;
    margin-left: 5%;
    margin-right: 5%;
    text-align: center;
    h3 {
        font-size: 1.1rem;  
    } 
    h4 {
        font-size: 1.1rem; 
        font-weight: 200;
    }    
 }
 #app-intro-content {
    padding: 0.5%;
 }
</code></pre>

<h4 id="appmenubutton-component">AppMenuButton Component</h4>

<ul>
  <li>
    <p>Create an <code>AppMenuButton</code> React component</p>

    <pre><code class="language-bash"> npx generate-react-cli component AppMenuButton 
</code></pre>
  </li>
  <li>
    <p>In your Editor replace the code of <code>AppMenuButton/AppMenuButton.tsx</code> with</p>
  </li>
</ul>

<pre><code class="language-ts"> import React from 'react';
 import './AppMenuButton.css';
 import { IonMenuButton } from '@ionic/react';

 interface AppMenuButtonProps {}

 const AppMenuButton: React.FC&lt;AppMenuButtonProps&gt; = () =&gt; {
  return (
    &lt;IonMenuButton slot="end" /&gt;
  )
 };

 export default AppMenuButton;
</code></pre>

<h4 id="authors-page">Authors Page</h4>

<ul>
  <li>
    <p>Under <code>src/pages</code> directory create the following files <code>AuthorsPage.css</code> and <code>AuthorsPage.tsx</code>.</p>
  </li>
  <li>
    <p>Open the <code>AuthorsPage.tsx</code></p>
  </li>
</ul>

<pre><code class="language-ts"> import React, { useState } from 'react';
 import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonCard,
        IonButtons, IonBackButton, IonIcon, useIonViewWillEnter } from '@ionic/react';
 import './AuthorsPage.css';
 import { save } from 'ionicons/icons';

 import sqliteParams from '../databases/sqliteParams';
 import authorDataSource from '../databases/datasources/AuthorDataSource';
 import { Post } from '../databases/entities/author/post';
 import { Category } from '../databases/entities/author/category';
 import { Author } from '../databases/entities/author/author';
 import { getCountOfElements } from '../databases/utilities';
 import PostList from '../components/PostList/PostList';

 const AuthorsPage: React.FC = () =&gt; {
    const [initialRef, setInitialRef] = useState(false);
    const [isWeb, setIsWeb] = useState(false);
    const [authors, setAuthors] = useState&lt;Author[]&gt;([]);
    const [categories, setCategories] = useState&lt;Category[]&gt;([]);
    const [posts, setPosts] = useState&lt;Post[]&gt;([]);
    let errMess = '';

    const connection = authorDataSource.dataSource;
    const database = authorDataSource.dbName;

    const createAuthor = async (name:string, email:string): Promise&lt;Author&gt; =&gt; {
        const author = new Author();
        author.name = name;
        author.email = email;
        const authorRepository = connection.getRepository(Author);
        let authorToUpdate = await authorRepository.findOne({
            where: {
            email: author.email,
            },
        });
        if (authorToUpdate != null) {
            author.id = authorToUpdate.id;
        }
        await authorRepository.save(author);
        return author;
    }; 
    const createCategory = async (name: string): Promise&lt;Category&gt; =&gt; {
        const category = new Category();
        category.name = name;
        const categoryRepository = connection.getRepository(Category);
        let categoryToUpdate = await categoryRepository.findOne({
          where: {
            name: category.name,
          },
        });
        if (categoryToUpdate != null) {
            category.id = categoryToUpdate.id;
        }
        await categoryRepository.save(category);
        return category;
    }; 
    const createPost = async (title: string, text: string, author:Author,
                              categories: Category[]): Promise&lt;void&gt; =&gt; {

        const post = new Post();
        post.title = title;
        post.text = text;
        post.author = author;
        post.categories = categories;
        const postRepository = connection.getRepository(Post);
        let postToUpdate = await postRepository.findOne({
          where: {
            title: post.title,
          },
        });
        if (postToUpdate != null) {
            post.id = postToUpdate.id;
        }
        await postRepository.save(post);
        return ;
    }; 
    const initializePosts = async () =&gt; {
        try {
            setIsWeb(sqliteParams.platform === 'web' ? true : false);
            const countAuthor = await getCountOfElements(connection, Author);
            if (countAuthor === 0 ) {
                // Create some Authors
                const author1 = await createAuthor('JeepQ', 'jeepq@example.com');
                const author2 = await createAuthor('Rosenwasser', 'rosenwasser@example.com');
                // Create some Categories
                const categ1 = await createCategory('Typescript');
                const categ2 = await createCategory('Programming');
                const categ3 = await createCategory('Tutorial');
                // Create some Posts
                await createPost('Announcing TypeScript 5.0',
                'This release brings many new features, while aiming to make TypeScript smaller, simpler, and faster...',
                author2,[categ1,categ2])
                await createPost('Ionic 7 SQLite Database CRUD App Example Tutorial using Angular and @capacitor-community/sqlite',
                'In that tutorial we will learned how to create a Ionic7/Angular basic CRUD application and implement the @capacitor-community/sqlite plugin to store the data in a SQLite database...',
                author1,[categ1,categ2,categ3])
                await createPost('Ionic 7 VideoPlayer App Example Tutorial using Angular and capacitor-video-player plugin',
                'In this tutorial, we will learn how to create a simple Ionic7/Angular video player application by implementing the capacitor-video-player plugin to display a list of videos with some data and play a selected video in fullscreen mode...',
                author1,[categ1,categ2,categ3])
                if (isWeb) {        
                    await sqliteParams.connection.saveToStore(database);
                }
            }
            setAuthors(await connection.manager.find(Author));
            setCategories(await connection.manager.find(Category));
            setPosts(await connection
                    .createQueryBuilder(Post,'post')
            .innerJoinAndSelect('post.author', 'author')
            .innerJoinAndSelect('post.categories', 'categories')
            .orderBy('author.name,post.title')
            .getMany());
            
        } catch (e) {
            console.log((e as any).message);
            errMess = `Error: ${(e as any).message}`;
        }               
    };
              
    const handleSave = (async () =&gt; {
        await sqliteParams.connection.saveToStore(database);
        // write database to local disk for development only
        await sqliteParams.connection.saveToLocalDisk(database);

    });

    useIonViewWillEnter( () =&gt; {
        if(initialRef === false) {
            initializePosts();
            setInitialRef(true);
          }

    });

    return (
        &lt;IonPage className="AuthorPage"&gt;
            &lt;IonHeader&gt;
                &lt;IonToolbar&gt;
                &lt;IonTitle&gt;Authors DB&lt;/IonTitle&gt;
                &lt;IonButtons slot="start"&gt;
                    &lt;IonBackButton text="home" defaultHref="/home"&gt;&lt;/IonBackButton&gt;
                &lt;/IonButtons&gt;
                {isWeb &amp;&amp; (
                    &lt;IonButtons slot="end"&gt;
                        &lt;IonIcon icon={save} onClick={handleSave}&gt;&lt;/IonIcon&gt;
                    &lt;/IonButtons&gt;
                )}
                &lt;/IonToolbar&gt;
            &lt;/IonHeader&gt;
            &lt;IonContent&gt;
            {initialRef &amp;&amp; (
                    &lt;div&gt;
                        &lt;IonCard v-if="errMess.length &gt; 0"&gt;
                            &lt;p&gt;{errMess}&lt;/p&gt;
                        &lt;/IonCard&gt;
                        &lt;div id="userlist-container"&gt;
                            &lt;PostList posts={posts}/&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                )}
            &lt;/IonContent&gt;
        &lt;/IonPage&gt;
    );
      
 } 
 export default AuthorsPage;

</code></pre>

<h4 id="postlist-component">PostList Component</h4>

<ul>
  <li>
    <p>Create an <code>PostList</code> React component</p>

    <pre><code class="language-bash"> npx generate-react-cli component PostList 
</code></pre>
  </li>
  <li>
    <p>In your Editor replace the code of <code>PostList/PostList.tsx</code> with</p>
  </li>
</ul>

<pre><code class="language-ts"> import React from 'react';
 import './PostList.css';
 import { IonList,IonLabel, IonListHeader, IonCard, IonCardHeader,
         IonCardTitle, IonCardSubtitle, IonCardContent } from '@ionic/react';
 import { Post } from '../../databases/entities/author/post';

 interface PostListProps {
  posts: Post[] }

 const PostList: React.FC&lt;PostListProps&gt; = ({posts}) =&gt; {

  const getCategories = (post: Post) =&gt; {
      const categories: string = post.categories.map(cat =&gt; cat.name).join(", ");
      return categories;
  }
  return (
    &lt;IonList className="PostList"&gt;
      &lt;IonListHeader id= "post-ion-list-header"&gt;
        &lt;IonLabel&gt;Post's List&lt;/IonLabel&gt;
      &lt;/IonListHeader&gt;
      {posts &amp;&amp; posts.map((post: Post) =&gt; (
        &lt;IonCard key={post.id}&gt;
          &lt;IonCardHeader&gt;
            &lt;IonCardTitle&gt;{post.title}&lt;/IonCardTitle&gt;
            &lt;IonCardSubtitle class="post-author-subtitle"&gt;{post.author.name}&lt;/IonCardSubtitle&gt;
            &lt;IonCardSubtitle class="post-categories-subtitle"&gt;{getCategories(post)}&lt;/IonCardSubtitle&gt;
          &lt;/IonCardHeader&gt;
          &lt;IonCardContent&gt;
            &lt;IonLabel&gt;{post.text}&lt;/IonLabel&gt;
          &lt;/IonCardContent&gt;
        &lt;/IonCard&gt;
      ))}
    &lt;/IonList&gt;
  )
 };

 export default PostList;

</code></pre>

<ul>
  <li>In your Editor replace the code of <code>PostList/PostList.css</code> with</li>
</ul>

<pre><code class="language-css"> .PostList {
    #post-ion-list-header {
        text-align: center;
        font-weight: bold;
        font-size: 2rem;
    }
    .post-author-subtitle {
        font-size: 1.15rem;
        font-weight: 500;
        font-style: italic;
        color:antiquewhite;
    }
    .post-categories-subtitle {
        font-size: 1.07rem;
        font-weight: 400;
        font-style: oblique;
        color:antiquewhite;
    }
    ion-card-content {
        font-size: 1rem;
    }
 }
</code></pre>

<h4 id="users-page">Users Page</h4>

<ul>
  <li>
    <p>Under <code>src/pages</code> directory create the following files <code>UsersPage.css</code> and <code>UsersPage.tsx</code>.</p>
  </li>
  <li>
    <p>Open the <code>UsersPage.tsx</code></p>
  </li>
</ul>

<pre><code class="language-ts"> import React from 'react';
 import './UserList.css';
 import { IonList, IonLabel, IonListHeader,
         IonCard, IonCardHeader, IonCardTitle, IonCardContent } from '@ionic/react';
 import { User } from '../../databases/entities/user/user';
 import { Item } from '../../databases/entities/user/item';

 interface UserListProps {
  users: User[] }

 const UserList: React.FC&lt;UserListProps&gt; = ({users}) =&gt; {

  return (
    &lt;IonList className="UserList"&gt;
      &lt;IonListHeader id= "users-ion-list-header"&gt;
        &lt;IonLabel&gt;User's List&lt;/IonLabel&gt;
      &lt;/IonListHeader&gt;
      {users &amp;&amp; users.map((user: User) =&gt; (
        &lt;IonCard key={user.id}&gt;
          &lt;IonCardHeader&gt;
            &lt;IonCardTitle&gt;{user.firstName} {user.lastName}&lt;/IonCardTitle&gt;
          &lt;/IonCardHeader&gt;
          &lt;IonCardContent&gt;
              &lt;ul&gt;
                {user.items &amp;&amp; user.items.map((item: Item) =&gt; 
                  &lt;li key={`${user.id}-${item.id}}`}&gt;
                    {item.name} {item.phoneNumber}
                  &lt;/li&gt;
                )}
              &lt;/ul&gt;
          &lt;/IonCardContent&gt;
        &lt;/IonCard&gt;
      ))}
    &lt;/IonList&gt;
  )
 };

 export default UserList;

</code></pre>

<h4 id="userlist-component">UserList Component</h4>

<ul>
  <li>
    <p>Create an <code>UserList</code> React component</p>

    <pre><code class="language-bash"> npx generate-react-cli component UserList 
</code></pre>
  </li>
  <li>
    <p>In your Editor replace the code of <code>UserList/UserList.tsx</code> with</p>
  </li>
</ul>

<pre><code class="language-ts"> import React from 'react';
 import './UserList.css';
 import { IonList, IonLabel, IonListHeader,
         IonCard, IonCardHeader, IonCardTitle, IonCardContent } from '@ionic/react';
 import { User } from '../../databases/entities/user/user';
 import { Item } from '../../databases/entities/user/item';

 interface UserListProps {
  users: User[] }

 const UserList: React.FC&lt;UserListProps&gt; = ({users}) =&gt; {

  return (
    &lt;IonList className="UserList"&gt;
      &lt;IonListHeader id= "users-ion-list-header"&gt;
        &lt;IonLabel&gt;User's List&lt;/IonLabel&gt;
      &lt;/IonListHeader&gt;
      {users &amp;&amp; users.map((user: User) =&gt; (
        &lt;IonCard key={user.id}&gt;
          &lt;IonCardHeader&gt;
            &lt;IonCardTitle&gt;{user.firstName} {user.lastName}&lt;/IonCardTitle&gt;
          &lt;/IonCardHeader&gt;
          &lt;IonCardContent&gt;
              &lt;ul&gt;
                {user.items &amp;&amp; user.items.map((item: Item) =&gt; 
                  &lt;li key={`${user.id}-${item.id}}`}&gt;
                    {item.name} {item.phoneNumber}
                  &lt;/li&gt;
                )}
              &lt;/ul&gt;
          &lt;/IonCardContent&gt;
        &lt;/IonCard&gt;
      ))}
    &lt;/IonList&gt;
  )
 };

 export default UserList;

</code></pre>

<ul>
  <li>Open <code>UserList/UserList.css</code> file</li>
</ul>

<pre><code class="language-css"> .UserList {
    #users-ion-list-header {
        text-align: center;
        font-weight: bold;
        font-size: 2rem;
    }
    ion-card-content {
        font-size: 1rem;
    }
 }
</code></pre>

<h3 id="run-the-web-sqlite-app">Run the Web SQLite App</h3>

<ul>
  <li>
    <p>To run the Web app use the below command</p>

    <pre><code class="language-bash"> npm run dev
</code></pre>
  </li>
  <li>
    <p>In your favorite Browser enter</p>

    <pre><code> http://localhost:5173/
</code></pre>
  </li>
  <li>
    <p>This will bring you to the <code>Home</code> page</p>

    <div align="center"><br /><img src="/images/Part1-Web-TypeOrm-React-SQLite-Home.png" width="500" /></div>
    <p><br /></p>
  </li>
  <li>
    <p>To open the menu, click on the <span style="font-size: 24px;"><ion-icon name="menu"></ion-icon></span> icon in the top right corner.</p>

    <div align="center"><br /><img src="/images/Part1-Web-TypeOrm-React-SQLite-Menu.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p> In the <strong><code>Menu Content</code></strong> click on <strong><code>Author's List</code></strong></p>

    <div align="center"><br /><img src="/images/Part1-Web-TypeOrm-React-SQLite-Author.png" width="250" /></div>
    <p><br /></p>
  </li>
</ul>

<p>The screenshot displays a list of posts. For each post, the author, categories, and text are retrieved from the database.</p>

<ul>
  <li>
    <p>To save the database on local disk, click on the <span style="font-size: 24px;"><ion-icon name="save"></ion-icon></span> icon in the top right corner.</p>

    <div align="center"><br /><img src="/images/Part1-Web-TypeOrm-React-SQLite-Save.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p> In the file picker select `Documents/CapacitorSQLite/YOUR_APPLICATION_NAME/YOUR_DATABASE_NAME` and click on `Save`</p>

    <div align="center"><br /><img src="/images/Part1-Web-TypeOrm-React-SQLite-SavePicker.png" width="500" /></div>
    <p><br /></p>
  </li>
</ul>

<h3 id="generate-a-new-migration-on-author">Generate a New Migration on Author</h3>

<p>Next, we’ll incorporate a “company” field into the author entity and generate a new migration for the author database.</p>

<h4 id="entity-author">Entity Author</h4>

<ul>
  <li>Open the <code>src/databases/entities/author/author.ts</code>file and add a <code>company</code> field</li>
</ul>

<pre><code class="language-ts"> import {Entity, PrimaryGeneratedColumn, Column, OneToMany, CreateDateColumn} from 'typeorm';
 import {Post} from './post';

 @Entity('author')
 export class Author {

  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  name!: string;

  @Column({nullable: true})
  company!: string;
 
  @Column({nullable: true})
  birthday!: string;

  @Column({unique: true})
  email!: string;

  @OneToMany(type =&gt; Post, post =&gt; post.author)
  posts!: Post[];
  
 }
</code></pre>

<h4 id="add-a-script-in-packagejson">Add a Script in Package.json</h4>

<ul>
  <li>Open the <code>package.json</code> file and ad the following script:</li>
</ul>

<pre><code class="language-json"> "scripts": {
  ...

      "typeorm:migration:generate:refactoring1Author": "npx typeorm-ts-node-esm migration:generate src/databases/migrations/author/refactoring1AuthorPost -d src/databases/datasources/AuthorDataSource.ts",

  ...
 }
</code></pre>

<h4 id="generate-the-migration-in-typeorm-cli">Generate the Migration in TypeOrm CLI</h4>

<pre><code class="language-bash"> npm run typeorm:migration:generate:refactoring1Author
</code></pre>

<p>you will get this message on the terminal</p>

<pre><code> new columns added: company
 Migration /Volumes/Development_Lacie/Development/blog/blog-tutorials-apps/SQLite/Part-1/typeorm-ionic7-react-sqlite-app/src/databases/migrations/author/1708331021699-refactoring1AuthorPost.ts has been generated successfully.
</code></pre>

<h4 id="add-the-migration-to-the-authordatasource">Add the Migration to the AuthorDataSource</h4>

<ul>
  <li>Open the <code>src/databases/migrations/author/index.ts</code>file and modify it</li>
</ul>

<pre><code class="language-ts"> import {InitialAuthorPost1708269296396} from './1708269296396-InitialAuthorPost';
 import {Refactoring1AuthorPost1708331021699} from './1708331021699-refactoring1AuthorPost'
 export {InitialAuthorPost1708269296396, Refactoring1AuthorPost1708331021699};
</code></pre>

<h4 id="execute-the-migration-in-the-web-app">Execute the Migration in the Web App</h4>

<pre><code class="language-bash">  npm run dev
</code></pre>

<ul>
  <li>
    <p>Then in the <code>Home</code> page</p>

    <div align="center"><br /><img src="/images/Part1-Web-TypeOrm-React-SQLite-Home-Migration.png" width="500" /></div>
    <p><br /></p>
  </li>
</ul>

<p>The Migration Refactoring1AuthorPost1708331021699 has been  executed successfully.</p>

<h3 id="part-1-conclusion">Part 1 Conclusion</h3>

<p>We have completed the Part 1 - Web application of the Ionic 7 TypeOrm SQLite Database App Example Tutorial using React and @capacitor-community/sqlite.</p>

<p>We learned how to generate the initial migration using the TypeOrm CLI.</p>

<p>We learned how to implement TypeOrm package and the ‘@capacitor-community/sqlite’ plugin in the React Framework using standalone components on a Web platform.</p>

<p>We’ve acquired knowledge on crafting an application menu, pages, and tailored components for showcasing lists of authors and users.</p>

<p>We learned how to utilize basic TypeOrm methods to create databases for authors and users, enabling the storage of persistent SQLite data in the Web IndexedDB browser database.</p>

<p>We gained insight into appending a new field, <code>company</code>, to the author entity and leveraged the TypeORM CLI to produce a new migration.</p>

<p>Enjoy your development from there.</p>

<h2 id="part-2---native---table-of-contents">Part 2 - Native - Table of Contents</h2>

<p>Work in Progress</p>]]></content><author><name>Quéau Jean Pierre</name></author><category term="Other" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Quasar SQLite Database CRUD App Example Tutorial using @capacitor-community/sqlite</title><link href="https://jepiqueau.github.io/2023/11/28/Quasar-SQLite-CRUD-App.html" rel="alternate" type="text/html" title="Quasar SQLite Database CRUD App Example Tutorial using @capacitor-community/sqlite" /><published>2023-11-28T00:00:00+00:00</published><updated>2023-11-28T00:00:00+00:00</updated><id>https://jepiqueau.github.io/2023/11/28/Quasar-SQLite-CRUD-App</id><content type="html" xml:base="https://jepiqueau.github.io/2023/11/28/Quasar-SQLite-CRUD-App.html"><![CDATA[<hr />

<p><em>last updated on December 2, 2023 by Quéau Jean Pierre</em></p>

<p>In that tutorial we will learned how to create a Quasar basic CRUD application and implement the @capacitor-community/sqlite plugin to store the data in a SQLite database.</p>

<p>The first part of the tutorial will concentrate on:</p>
<ul>
  <li>how to create that application and run it on a Web browser where the data will be stored on an Indexed database using sql.js and localForage modules.</li>
  <li>how to use the upgrade statement to create a version 2 of the database by altering the datacase’s schema.</li>
</ul>

<p>Go to <a href="#part-1---web---table-of-contents">Part 1 - Web - Table of Contents</a></p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/SQLite/Part-1/quasar-sqlite-app">Part-1/quasar-sqlite-app</a></p>

<p>Thanks to the Ionic Team and their hard work to bring CAPACITOR 5, the second part will concentrate on native platforms (iOS and Android) and also on Electron platform.
Go to <a href="#part-2---native---table-of-contents">Part 2 - Native - Table of Contents</a></p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/SQLite/Part-2/quasar-sqlite-app">Part-2/quasar-sqlite-app</a></p>

<h2 id="part-1---web---table-of-contents">Part 1 - Web - Table of Contents</h2>

<hr />
<ul>
  <li><a href="#install-new-quasar-application">Install New Quasar Application</a></li>
  <li><a href="#install-capacitor">Install Capacitor</a></li>
  <li><a href="#install-required-packages">Install Required Packages</a></li>
  <li><a href="#create-the-sqlite-database">Create the SQLite Database</a></li>
  <li><a href="#create-crud-and-sqlite-services">Create CRUD and SQLite Services</a></li>
  <li><a href="#quasar-plugin-implementation">Quasar Plugin Implementation</a></li>
  <li><a href="#modify-the-home-page">Modify the Home Page</a></li>
  <li><a href="#modify-the-main-layout">Modify the Main Layout</a></li>
  <li><a href="#users-page-implementation">Users Page Implementation</a></li>
  <li><a href="#users-component-implementation">Users Component Implementation</a></li>
  <li><a href="#create-the-querysqlite-hook">Create the QuerySQLite Hook</a></li>
  <li><a href="#update-config">Update Config</a></li>
  <li><a href="#run-the-web-sqlite-app">Run the Web SQLite App</a></li>
  <li><a href="#video-storyboard">Video Storyboard</a></li>
  <li><a href="#upgrade-database-to-version-2">Upgrade Database to Version 2</a></li>
  <li><a href="#part-1-conclusion">Part 1 Conclusion</a></li>
</ul>

<hr />

<h3 id="install-new-quasar-application">Install New Quasar Application</h3>

<ul>
  <li>
    <p>Install the latest version of Quasar CLI globally installed on your device, run the below command.</p>

    <pre><code class="language-bash"> npm install -g @quasar/cli
</code></pre>
  </li>
  <li>
    <p>Create a new Quasar app</p>

    <pre><code class="language-bash"> npm init quasar
</code></pre>

    <p>You’ll be prompted with some options:</p>

    <ul>
      <li>App with Quasar CLI, let’s go!</li>
      <li>Project folder: <code>quasar-sqlite-app</code></li>
      <li>Pick Quasar Version: <code>Quasar V2 (Vue 3 | latest and greatest)</code></li>
      <li>Pick Script Type: <code>Typescript</code></li>
      <li>Pick Quasar App Cli variant: <code>Quasar App CLI with Vite</code></li>
      <li>Package name: <code>quasar-sqlite-app</code></li>
      <li>Project product name: <code>Quasar SQLite App</code></li>
      <li>Project description: <code>A Quasar SQLite Capacitor Project</code></li>
      <li>Author: <code>YOUR_NAME</code></li>
      <li>Pick a Vue component style: <code>Composition API</code></li>
      <li>Pick your CSS preprocessor: <code>None</code></li>
      <li>Check the features needed for your project: <code>ESLint</code></li>
      <li>Pick an ESLint preset: <code>Prettier</code></li>
      <li>Install project dependencies?: <code>Yes, use npm</code></li>
    </ul>
  </li>
  <li>
    <p>Test the application</p>
  </li>
</ul>

<pre><code class="language-bash">  cd quasar-sqlite-app
  npm run dev
</code></pre>
<p>Opening default browser at http://localhost:9000/</p>

<p>Yow must see a Quasar App with a menu <code>Essentials Links</code> and an <code>Example component</code>.</p>

<h3 id="install-capacitor">Install Capacitor</h3>

<p>You must install the latest version of <code>@capacitor/core</code> and <code>@capacitor/cli</code>.</p>

<pre><code class="language-bash">    npm i @capacitor/core
    npm i -D @capacitor/cli
</code></pre>

<p>Then, initialize your Capacitor config.</p>

<pre><code class="language-bash">    npx cap init
</code></pre>

<p>You’ll be prompted with some options:</p>

<ul>
  <li>What is the name of your app?: <code>quasar-sqlite-app</code></li>
  <li>What should be the Package ID for your app?: <code>YOUR_PACKAGE_ID</code></li>
  <li>What is the web asset directory for your app?: <code>dist/spa</code></li>
</ul>

<p>When done, you must get [success] capacitor.config.ts created!</p>

<h3 id="install-required-packages">Install Required Packages</h3>

<ul>
  <li>
    <p>run the below commands</p>

    <pre><code class="language-bash"> npm i @capacitor-community/sqlite
 npm i @capacitor/toast
 npm i @ionic/pwa-elements
 npm i -D copyfiles
</code></pre>
  </li>
</ul>

<h3 id="create-the-sqlite-database">Create the SQLite Database</h3>

<ul>
  <li>
    <p>To easily upgrade the database from one version to the next, the database is created through an upgrade statement. In your editor, create a folder <code>upgrades</code> under the <code>src</code> folder and then create a new file <code>upgrades/user.statements.ts</code>.</p>
  </li>
  <li>
    <p>Define the upgrade statements in <code>upgrades/user.upgrade.statements.ts</code> file</p>

    <pre><code class="language-ts"> export const UserUpgradeStatements = [
     {
         toVersion: 1,
         statements: [
             `CREATE TABLE IF NOT EXISTS users (
             id INTEGER PRIMARY KEY AUTOINCREMENT,
             name TEXT NOT NULL,
             active INTEGER DEFAULT 1
             );`
         ]
     },
     /* add new statements below for next database version when required*/
     /*
     {
         toVersion: 2,
         statements: [
             `ALTER TABLE users ADD COLUMN email TEXT;`,
         ]
     },
     */
 ]
   
</code></pre>
  </li>
  <li>
    <p>Define the User Model</p>

    <p>In your editor, create a folder <code>models</code> under the <code>src</code> folder and then create a new file <code>models/user.ts</code>.</p>
  </li>
  <li>
    <p>Update the <code>models/user.ts</code> file as</p>

    <pre><code class="language-ts"> export interface User {
     id: number;
     name: string;
     active: number;
     /*
     email: string; // Version 2
     */
 }
</code></pre>
  </li>
</ul>

<h3 id="create-crud-and-sqlite-services">Create CRUD and SQLite Services</h3>

<p>The CRUD service will be dedicated to the CRUD operations of the application like:</p>

<ul>
  <li>addUser,</li>
  <li>deleteUserById,</li>
  <li>getDatabaseName,</li>
  <li>getDatabaseVersion,</li>
  <li>getUsers,</li>
  <li>initializeDatabase,</li>
  <li>replaceUser,</li>
  <li>updateUserActiveById,</li>
</ul>

<p>While the SQLite service will be dealing with the API to the <code>@capacitor-community/sqlite</code> plugin including:</p>

<ul>
  <li>addUpgradeStatement,</li>
  <li>closeDatabase,</li>
  <li>getPlatform,</li>
  <li>initWebStore,</li>
  <li>isConnection,</li>
  <li>openDatabase,</li>
  <li>saveToStore,</li>
  <li>
    <p>saveToLocalDisk,</p>
  </li>
  <li>
    <p>To create CRUD and SQLite services, in your file editor, add a new <code>src/services</code> folder and create the two following files:</p>

    <ul>
      <li><code>services/sqliteService.ts</code></li>
      <li><code>services/storageService.ts</code></li>
    </ul>
  </li>
  <li>
    <p>Open the <code>services/sqliteService.ts</code> file and replace with the following code.</p>

    <pre><code class="language-ts"> import {
 CapacitorSQLite,
 SQLiteConnection,
 SQLiteDBConnection,
 capSQLiteUpgradeOptions,
 } from '@capacitor-community/sqlite';
 import { Capacitor } from '@capacitor/core';

 export interface ISQLiteService {
     addUpgradeStatement(options: capSQLiteUpgradeOptions): Promise&lt;void&gt;;
     closeDatabase(dbName: string, readOnly: boolean): Promise&lt;void&gt;;
     getPlatform(): string;
     initWebStore(): Promise&lt;void&gt;;
     isConnection(dbName: string, readOnly: boolean): Promise&lt;boolean&gt;;
     openDatabase(
         dbName: string,
         loadToVersion: number,
         readOnly: boolean
     ): Promise&lt;SQLiteDBConnection | undefined&gt;;
     saveToStore(dbName: string): Promise&lt;void&gt;;
     saveToLocalDisk(dbName: string): Promise&lt;void&gt;;
 }

 class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     async addUpgradeStatement(options: capSQLiteUpgradeOptions): Promise&lt;void&gt; {
         // add the upgrade statement to define the database schema
         // depending on the database version
         try {
         await this.sqlitePlugin.addUpgradeStatement(options);
         // eslint-disable-next-line @typescript-eslint/no-explicit-any
         } catch (error: any) {
         const msg = error.message ? error.message : error;
         throw new Error(`sqliteService.addUpgradeStatement: ${msg}`);
         }
         return;
     }

     async closeDatabase(dbName: string, readOnly: boolean): Promise&lt;void&gt; {
         // close the connection to the database and close the database
         try {
         const isConn = (
             await this.sqliteConnection.isConnection(dbName, readOnly)
         ).result;
         if (isConn) {
             await this.sqliteConnection.closeConnection(dbName, readOnly);
         }
         return;
         // eslint-disable-next-line @typescript-eslint/no-explicit-any
         } catch (error: any) {
         const msg = error.message ? error.message : error;
         throw new Error(`sqliteService.closeDatabase: ${msg}`);
         }
     }

     getPlatform(): string {
         // return the device platform
         return this.platform;
     }

     async initWebStore(): Promise&lt;void&gt; {
         // initialize the web store to store the database for web platform
         try {
         await this.sqliteConnection.initWebStore();
         // eslint-disable-next-line @typescript-eslint/no-explicit-any
         } catch (error: any) {
         const msg = error.message ? error.message : error;
         throw new Error(`sqliteService.initWebStore: ${msg}`);
         }
         return;
     }
     async isConnection(dbName: string, readOnly: boolean): Promise&lt;boolean&gt; {
         // check if a connection exist to the database
         try {
         const isConn = (
             await this.sqliteConnection.isConnection(dbName, readOnly)
         ).result;
         if (isConn != undefined) {
             return isConn;
         } else {
             throw new Error('sqliteService.isConnection undefined');
         }
         // eslint-disable-next-line @typescript-eslint/no-explicit-any
         } catch (error: any) {
         const msg: string = error.message ? error.message : error;
         throw new Error(`sqliteService.isConnection: ${msg}`);
         }
     }

     async openDatabase(
         dbName: string,
         loadToVersion: number,
         readOnly: boolean
     ): Promise&lt;SQLiteDBConnection | undefined&gt; {
         // create a database connection and open the database
         this.dbNameVersionDict.set(dbName, loadToVersion);
         const encrypted = false;
         const mode = encrypted ? 'secret' : 'no-encryption';
         try {
         let db: SQLiteDBConnection;
         const retCC = (await this.sqliteConnection.checkConnectionsConsistency())
             .result;
         const isConn = (
             await this.sqliteConnection.isConnection(dbName, readOnly)
         ).result;
         if (retCC &amp;&amp; isConn) {
             db = await this.sqliteConnection.retrieveConnection(dbName, readOnly);
         } else {
             db = await this.sqliteConnection.createConnection(
             dbName,
             encrypted,
             mode,
             loadToVersion,
             readOnly
             );
         }
         await db.open();
         const res = await db.isDBOpen();
         if (!res.result) {
             const msg = 'database is not opened';
             throw new Error(`sqliteService.openDatabase: ${msg}`);
         }
         return db;
         // eslint-disable-next-line @typescript-eslint/no-explicit-any
         } catch (error: any) {
         const msg = error.message ? error.message : error;
         throw new Error(`sqliteService.openDatabase: ${msg}`);
         }
     }

     async saveToLocalDisk(dbName: string): Promise&lt;void&gt; {
         // save the database to local disk for the Web platform
         try {
         await this.sqliteConnection.saveToLocalDisk(dbName);
         return;
         // eslint-disable-next-line @typescript-eslint/no-explicit-any
         } catch (err: any) {
         const msg = err.message ? err.message : err;
         throw new Error(`sqliteService.saveToLocalDisk: ${msg}`);
         }
     }

     async saveToStore(dbName: string): Promise&lt;void&gt; {
         // save the database to store for the Web platform
         try {
         await this.sqliteConnection.saveToStore(dbName);
         return;
         // eslint-disable-next-line @typescript-eslint/no-explicit-any
         } catch (error: any) {
         const msg = error.message ? error.message : error;
         throw new Error(`sqliteService.saveToStore: ${msg}`);
         }
     }
 }
 export default SQLiteService;
</code></pre>
  </li>
  <li>
    <p>Open the <code>services/storage.service.ts</code> and replace the code with</p>

    <pre><code class="language-ts"> import { BehaviorSubject } from 'rxjs';
 import { getCurrentInstance } from 'vue';
 import { ISQLiteService } from '../services/sqliteService';
 import { IDbVersionService } from '../services/dbVersionService';
 import { SQLiteDBConnection } from '@capacitor-community/sqlite';
 import { UserUpgradeStatements } from '../upgrades/user.statements';
 import { User } from '../models/User';

 export interface IStorageService {
     addUser(user: User): Promise&lt;number&gt;;
     deleteUserById(id: string): Promise&lt;void&gt;;
     getDatabaseName(): string;
     getDatabaseVersion(): number;
     getUsers(): Promise&lt;User[]&gt;;
     initializeDatabase(): Promise&lt;void&gt;;
     replaceUser(user: User): Promise&lt;void&gt;;
     updateUserActiveById(id: string, active: number): Promise&lt;void&gt;;
 }
 class StorageService implements IStorageService {
     versionUpgrades = UserUpgradeStatements;
     loadToVersion =
         UserUpgradeStatements[UserUpgradeStatements.length - 1].toVersion;
     db!: SQLiteDBConnection | undefined;
     database = 'myuserdb';
     sqliteServ!: ISQLiteService;
     dbVerServ!: IDbVersionService;
     isInitCompleted = new BehaviorSubject(false);
     appInstance = getCurrentInstance();
     platform!: string;

     constructor(
         sqliteService: ISQLiteService,
         dbVersionService: IDbVersionService
     ) {
         this.sqliteServ = sqliteService;
         this.dbVerServ = dbVersionService;
         this.platform =
         this.appInstance?.appContext.config.globalProperties.$platform;
     }

     async addUser(user: User): Promise&lt;number&gt; {
         // add a user to the database
         const colList = Object.keys(user).slice(1).toString();
         const valArr = Object.values(user).slice(1);
         const valList: string = valArr
             .map((value) =&gt; (typeof value === 'string' ? `'${value}'` : value))
             .join(',');

         const sql = `INSERT INTO users (${colList}) VALUES (${valList});`;
         const res = await this.db?.run(sql, []);
         if (
             res?.changes !== undefined &amp;&amp;
             res.changes.lastId !== undefined &amp;&amp;
             res.changes.lastId &gt; 0
         ) {
             return res.changes.lastId;
         } else {
             throw new Error('storageService.addUser: lastId not returned');
         }
     }

     async deleteUserById(id: string): Promise&lt;void&gt; {
         // delete a user by id from the database
         const sql = `DELETE FROM users WHERE id=${id}`;
         await this.db?.run(sql);
     }

     getDatabaseName(): string {
         // return the database name
         return this.database;
     }

     getDatabaseVersion(): number {
         // return the database version
         return this.loadToVersion;
     }

     async getUsers(): Promise&lt;User[]&gt; {
         // return all users
         return (await this.db?.query('SELECT * FROM users;'))?.values as User[];
     }

     async initializeDatabase(): Promise&lt;void&gt; {
         // initialize the database
         try {
             // create upgrade statements
             await this.sqliteServ.addUpgradeStatement({
                 database: this.database,
                 upgrade: this.versionUpgrades,
             });
             // open the connection to the database with the latest version
             // and then open the database
             this.db = await this.sqliteServ.openDatabase(
                 this.database,
                 this.loadToVersion,
                 false
             );
             const isData = await this.db?.query('select * from sqlite_sequence');
             if (isData?.values &amp;&amp; isData.values.length === 0) {
                 // create database initial users if any
             }
             // store the database version
             this.dbVerServ.setDbVersion(this.database, this.loadToVersion);
             if (this.platform === 'web') {
                 await this.sqliteServ.saveToStore(this.database);
             }
             this.isInitCompleted.next(true);
         // eslint-disable-next-line @typescript-eslint/no-explicit-any
         } catch (error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`storageService.initializeDatabase: ${msg}`);
         }
     }

     async replaceUser(user: User): Promise&lt;void&gt; {
         const colList = Object.keys(user).toString();
         const valArr = Object.values(user);
         const valList: string = valArr
             .map((value) =&gt; (typeof value === 'string' ? `'${value}'` : value))
             .join(',');
         const sql = `INSERT OR REPLACE INTO users (${colList}) VALUES (${valList});`;
         const res = await this.db?.run(sql, []);
         if (
             res?.changes !== undefined &amp;&amp;
             res.changes.lastId !== undefined &amp;&amp;
             res.changes.lastId &gt; 0
         ) {
             return;
         } else {
             throw new Error('storageService.replaceUser: lastId not returned');
         }
     }

     async updateUserActiveById(id: string, active: number): Promise&lt;void&gt; {
         const sql = `UPDATE users SET active=${active} WHERE id=${id}`;
         await this.db?.run(sql);
     }
 }
 export default StorageService;
</code></pre>
  </li>
</ul>

<p>To manage the database versionning, a new service <code>DbnameVersionService</code> is required. In your file editor, go to <code>src/services</code> folder and create the <code>dbVersionService.ts</code> file</p>

<ul>
  <li>
    <p>Open the <code>services/dbVersionService.ts</code> file and replace the code with</p>

    <pre><code class="language-ts"> export interface IDbVersionService {
     getDbVersion(dbName: string):number| undefined
     setDbVersion(dbName: string, version: number): void
 };
 class DbVersionService implements IDbVersionService  {
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     getDbVersion(dbName: string): number | undefined {
         const version =  this.dbNameVersionDict.get(dbName);
         return version;
     };

     setDbVersion(dbName: string, version: number) {
         this.dbNameVersionDict.set(dbName, version);
     };
 }
 export default new DbVersionService();
</code></pre>
  </li>
</ul>

<h3 id="quasar-plugin-implementation">Quasar Plugin Implementation</h3>

<p>For Web applications, the plugin uses the Stencil component <code>jeep-sqlite</code> which implies to define it in  App.vue file and to copy the <code>sql-wasm.wasm</code>file to the <code>public/assets</code>folder.</p>

<ul>
  <li>Open the <code>package.json</code> and modify the script as follows:</li>
</ul>

<pre><code class="language-json">   "scripts": {
        "lint": "eslint --ext .js,.ts,.vue ./",
        "format": "prettier --write \"**/*.{js,ts,vue,css,html,md,json}\" --ignore-path .gitignore",
        "test": "echo \"No test specified\" &amp;&amp; exit 0",
        "dev": "npm run copy:sql:wasm &amp;&amp; quasar dev",
        "build:web": "npm run copy:sql:wasm &amp;&amp; quasar build",
        "copy:sql:wasm": "copyfiles -u 3 node_modules/sql.js/dist/sql-wasm.wasm public/assets"
    },
</code></pre>

<p>As the goal is to ensure that the services (<code>SqliteService</code>, <code>DbVersionService</code> and <code>StorageService</code>) are unique and properly shared and available throughout the components, they have been defined in the App.vue file, to be injected in components.</p>

<p>During the mounting of the app an <code>InitializeAppService</code> service is used to initialize the application and has to be created.</p>

<ul>
  <li>
    <p>In your Editor add a new file <code>initializeAppService.ts</code> file under the folder <code>src/services</code>.</p>
  </li>
  <li>
    <p>In your editor, open the file <code>services/initializeAppService.ts</code> and replace the code with:</p>

    <pre><code class="language-ts"> import { ISQLiteService } from '../services/sqliteService';
 import { IStorageService } from '../services/storageService';

 export interface IInitializeAppService {
 initializeApp(): Promise&lt;boolean&gt;;
 }

 class InitializeAppService implements IInitializeAppService {
     appInit = false;
     sqliteServ!: ISQLiteService;
     storageServ!: IStorageService;
     platform!: string;

     constructor(sqliteService: ISQLiteService, storageService: IStorageService) {
         this.sqliteServ = sqliteService;
         this.storageServ = storageService;
         this.platform = this.sqliteServ.getPlatform();
     }
     async initializeApp(): Promise&lt;boolean&gt; {
         if (!this.appInit) {
             try {
                 if (this.platform === 'web') {
                 await this.sqliteServ.initWebStore();
                 }
                 // Initialize the myuserdb database
                 await this.storageServ.initializeDatabase();
                 if (this.platform === 'web') {
                 await this.sqliteServ.saveToStore(this.storageServ.getDatabaseName());
                 }
                 this.appInit = true;
                 // eslint-disable-next-line @typescript-eslint/no-explicit-any
             } catch (error: any) {
                 const msg = error.message ? error.message : error;
                 throw new Error(`initializeAppError.initializeApp: ${msg}`);
             }
         }
         return this.appInit;
     }
 }
 export default InitializeAppService;
</code></pre>
  </li>
  <li>
    <p>Open the <code>App.vue</code> file  and replace the code with</p>

    <pre><code class="language-ts"> &lt;template&gt;
     &lt;router-view /&gt;
 &lt;/template&gt;

 &lt;script lang="ts"&gt;
     import { defineComponent, onMounted } from 'vue';
     import { Capacitor } from '@capacitor/core';
     import { defineCustomElements as pwaElements } from '@ionic/pwa-elements/loader';
     import { JeepSqlite } from 'jeep-sqlite/dist/components/jeep-sqlite';
     import SqliteService from './services/sqliteService';
     import DbVersionService from './services/dbVersionService';
     import StorageService from './services/storageService';
     import InitializeAppService from './services/initializeAppService';

     // initialize pwaElements for Toast in Web platform
     pwaElements(window);
     // Define services as unique
     const sqliteServ = new SqliteService();
     const dbVersionServ = new DbVersionService();
     const storageServ = new StorageService(sqliteServ, dbVersionServ);

     export default defineComponent({
         name: 'App',
         provide: {
             sqliteServ,
             dbVersionServ,
             storageServ,
         },

         setup() {
             customElements.define('jeep-sqlite', JeepSqlite);
             const platform = Capacitor.getPlatform();
             //Define and instantiate the InitializeAppService
             const initAppServ = new InitializeAppService(sqliteServ, storageServ);

             const initApp = async () =&gt; {
                 try {
                     await initAppServ.initializeApp();
                 } catch (error) {
                     console.error('App Initialization error:', error);
                 }
             };
             onMounted(async () =&gt; {
                 if (platform != 'web') {
                     await initApp();
                 } else {
                     const jeepEl = document.createElement('jeep-sqlite');
                     document.body.appendChild(jeepEl);
                     customElements
                     .whenDefined('jeep-sqlite')
                     .then(async () =&gt; {
                         await initApp();
                     })
                     .catch((err) =&gt; {
                         console.error('jeep-sqlite creation error:', err);
                     });
                 }
             });
             return {};
         },
     });
 &lt;/script&gt;
</code></pre>
  </li>
</ul>

<h3 id="modify-the-home-page">Modify the Home Page</h3>

<p>The <code>Index</code> page will be modify to include:</p>

<pre><code>- a company logo
- a welcome text
</code></pre>

<p>This will be achieved by creating new components that will be integrated in the <code>Index</code> page.</p>

<ul>
  <li>Edit the <code>IndexPage.vue</code> file under the <code>pages</code> folder.</li>
</ul>

<pre><code class="language-ts">    &lt;template&gt;
    &lt;q-page&gt;
        &lt;app-logo&gt;&lt;/app-logo&gt;
        &lt;app-intro-text&gt;&lt;/app-intro-text&gt;
    &lt;/q-page&gt;
    &lt;/template&gt;

    &lt;script lang="ts"&gt;
        import { defineComponent } from 'vue';
        import AppLogo from 'components/AppLogo.vue';
        import AppIntroText from 'components/AppIntroText.vue';

        export default defineComponent({
        name: 'IndexPage',
        components: { AppLogo, AppIntroText },
        setup() {
            return {};
        },
        });
    &lt;/script&gt;
</code></pre>

<ul>
  <li>
    <p>Create an <code>AppLogo</code> component</p>

    <ul>
      <li>
        <p>In your Editor create a <code>AppLogo.vue</code> file under <code>src/components</code>folder and copy the following code</p>

        <pre><code class="language-ts">  &lt;template&gt;
      &lt;div class="AppLogo"&gt;
      &lt;img src="/assets/JeepQLogo.png" alt="App Logo" width="128" height="128" /&gt;
      &lt;/div&gt;
  &lt;/template&gt;
        
  &lt;script lang="ts"&gt;
      import { defineComponent } from 'vue';
      export default defineComponent({
          name: 'AppLogo',
      });
  &lt;/script&gt;

  &lt;style scoped&gt;
      .AppLogo {
          width: 100%;
          display: flex;
          justify-content: center;
          margin-top: 2rem;
          margin-bottom: 1rem;
      }
  &lt;/style&gt;
</code></pre>
      </li>
    </ul>
  </li>
</ul>

<p>Obviously use your own logo and store it in the <code>public/assets</code> folder.</p>

<ul>
  <li>
    <p>Create an <code>AppIntroText</code> component</p>

    <ul>
      <li>
        <p>In your Editor create a <code>AppIntroText.vue</code> file under <code>src/components</code>folder and copy the following code</p>

        <pre><code class="language-ts">  &lt;template&gt;
      &lt;div class="AppIntroText"&gt;
          &lt;h3&gt;Welcome to the Quasar SQLite Database CRUD App Example Tutorial&lt;/h3&gt;
          &lt;h5&gt;using @capacitor-community/sqlite&lt;/h5&gt;
      &lt;/div&gt;
  &lt;/template&gt;

  &lt;script lang="ts"&gt;
      import { defineComponent } from 'vue';
      export default defineComponent({
          name: 'AppIntroText',
      });
  &lt;/script&gt;

  &lt;style scoped&gt;
      .AppIntroText {
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          text-align: center;
          padding: 0.5rem;
      }
  &lt;/style&gt;
</code></pre>
      </li>
    </ul>
  </li>
</ul>

<p>Fill free to put whatever text you would like to see</p>

<ul>
  <li>Delete the <code>ExampleComponent.vue</code>component and the <code>models.ts</code>from the <code>src/components</code>folder</li>
</ul>

<h3 id="modify-the-main-layout">Modify the Main Layout</h3>

<p>The main layout will include a menu on the right, which will allow users to navigate through the application’s pages and return to the Home page.</p>

<ul>
  <li>Edit the <code>MainLayout.vue</code> file under the <code>src/layouts</code> folder and replace the code as below.</li>
</ul>

<pre><code class="language-ts">    &lt;template&gt;
    &lt;q-layout ref="layout" view="lHh Lpr lFf"&gt;
        &lt;q-header elevated&gt;
        &lt;q-toolbar&gt;
            &lt;q-btn v-if="isBack" @click="goBack"&gt;Back&lt;/q-btn&gt;
            &lt;q-toolbar-title&gt; &lt;/q-toolbar-title&gt;
            &lt;q-btn
            flat
            dense
            round
            icon="menu"
            aria-label="Menu"
            @click="toggleRightDrawer"
            /&gt;
        &lt;/q-toolbar&gt;
        &lt;/q-header&gt;

        &lt;q-drawer v-model="rightDrawerOpen" side="right" show-if-above bordered&gt;
        &lt;q-list&gt;
            &lt;q-item-label header&gt; Menu Content &lt;/q-item-label&gt;

            &lt;MenuRoute v-for="page in pages" :key="page.title" v-bind="page" /&gt;
        &lt;/q-list&gt;
        &lt;/q-drawer&gt;

        &lt;q-page-container&gt;
        &lt;router-view /&gt;
        &lt;/q-page-container&gt;
    &lt;/q-layout&gt;
    &lt;/template&gt;

    &lt;script lang="ts"&gt;
    import { defineComponent, ref } from 'vue';
    import MenuRoute from 'components/MenuRoute.vue';

    const pageList = [
        {
            title: 'Managing Users',
            name: 'users',
        },
    ];

    export default defineComponent({
        name: 'MainLayout',
        components: {
            MenuRoute,
        },

        setup() {
            const rightDrawerOpen = ref(false);
            return {
            pages: pageList,
            rightDrawerOpen,
            toggleRightDrawer() {
                rightDrawerOpen.value = !rightDrawerOpen.value;
            },
            };
        },
        data() {
            return {
            pageTitle: 'Quasar SQLite App', // Set your default title here
            isBack: false,
            };
        },
        watch: {
            // Watch for changes in the route and update the pageTitle accordingly
            $route(to) {
            if (to.name !== 'home') this.isBack = true;
            this.pageTitle = to.meta.title || 'Quasar SQLite App';
            },
        },
        methods: {
            goBack() {
            this.isBack = false;
            this.$router.push({ name: 'home' });
            },
        },
    });
    &lt;/script&gt;
</code></pre>

<ul>
  <li>Create the <code>MenuRoute.vue</code> component under the <code>src/components</code> and add the following code.</li>
</ul>

<pre><code class="language-ts">    &lt;template&gt;
    &lt;q-item clickable @click="onClick()"&gt;
        &lt;q-item-section&gt;
        &lt;q-item-label&gt;&lt;/q-item-label&gt;
        &lt;/q-item-section&gt;
    &lt;/q-item&gt;
    &lt;/template&gt;

    &lt;script lang="ts"&gt;
    import { defineComponent } from 'vue';

    export default defineComponent({
        name: 'MenuRoute',
        props: {
            title: {
            type: String,
            required: true,
            },

            name: {
            type: String,
            required: true,
            },
        },
        methods: {
            onClick() {
            this.$router.push({ name: this.$props.name });
            },
        },
    });
    &lt;/script&gt;
</code></pre>

<ul>
  <li>Delete the <code>EssentialLink.vue</code>component in the <code>src/components</code>folder.</li>
</ul>

<h3 id="users-page-implementation">Users Page Implementation</h3>

<p>The Users Page design will allow access to the CRUD operations. 
 Let’s create it.</p>

<ul>
  <li>
    <p>In your Editor, under <code>src/pages</code> folder add a new page <code>UsersPage.vue</code>.</p>
  </li>
  <li>
    <p>Then open the <code>UsersPage.vue</code> file and add the following code:</p>

    <pre><code class="language-ts"> &lt;template&gt;
     &lt;q-page&gt;
         &lt;div v-if="isInitComplete &amp;&amp; dbInitialized"&gt;
         &lt;q-card&gt;
             &lt;q-card-section&gt;
             &lt;div class="text-h5"&gt;Add New User&lt;/div&gt;
             &lt;user-form method="add" :onAddUser="handleAddUser"&gt;&lt;/user-form&gt;
             &lt;/q-card-section&gt;
         &lt;/q-card&gt;
         &lt;q-card&gt;
             &lt;q-card-section&gt;
             &lt;div class="text-h5"&gt;Current Users&lt;/div&gt;
             &lt;user-list
                 :users="users"
                 :onUpdateUserActive="handleUpdateUserActive"
                 :onDeleteUser="handleDeleteUser"
                 :onEditUser="handleEditUser"
             /&gt;
             &lt;/q-card-section&gt;
         &lt;/q-card&gt;
         &lt;!-- q-dialog for the centered inline modal content --&gt;
         &lt;q-dialog v-model="centeredModalOpen"&gt;
             &lt;q-card style="width: 60vw"&gt;
             &lt;q-card-section&gt;
                 &lt;!-- Modal content goes here --&gt;
                 &lt;div class="text-h5"&gt;Update User&lt;/div&gt;
                 &lt;user-form
                 method="update"
                 :onUpdateUser="handleUpdateUser"
                 :user="editUser"
                 &gt;&lt;/user-form&gt;
             &lt;/q-card-section&gt;
             &lt;/q-card&gt;
         &lt;/q-dialog&gt;
         &lt;/div&gt;
     &lt;/q-page&gt;
 &lt;/template&gt;

 &lt;script lang="ts"&gt;
 import {
 defineComponent,
 ref,
 inject,
 computed,
 onMounted,
 onBeforeUnmount,
 watch,
 } from 'vue';
 import UserForm from 'components/UserForm.vue';
 import UserList from 'components/UserList.vue';
 import { User } from '../models/User';
 import { SQLiteDBConnection } from '@capacitor-community/sqlite';
 import { Toast } from '@capacitor/toast';
 import { useQuerySQLite } from '../hooks/UseQuerySQLite';
 import SQLiteService from 'src/services/sqliteService';
 import StorageService from 'src/services/storageService';

 export default defineComponent({
     name: 'UsersPage',
     components: { UserForm, UserList },
     setup() {
         // Inject services
         const sqliteServ: SQLiteService | undefined = inject('sqliteServ');
         const storageServ: StorageService | undefined = inject('storageServ');
         // Define Internal variables
         const centeredModalOpen = ref(false);
         const centeredModalMarginTop = ref('20vh');
         const db = ref&lt;SQLiteDBConnection | undefined&gt;(undefined);
         const dbInitialized = computed(() =&gt; !!db.value);
         const dbNameRef = ref('');
         const editUser = ref&lt;User&gt;({} as User);
         const isInitComplete = ref(false);
         const isDatabase = ref(false);
         const platform = sqliteServ?.getPlatform();
         const users = ref&lt;User[]&gt;([]);

         // Define methods
         const getAllUsers = async (db: SQLiteDBConnection) =&gt; {
             // Query the database to get all users
             const stmt = 'SELECT * FROM users';
             const values: never[] = [];
             const fetchData = await useQuerySQLite(db, stmt, values);
             users.value = fetchData;
         };

         const openDatabase = async () =&gt; {
             // Open the connection to the database
             try {
                 const dbUsersName = storageServ?.getDatabaseName() as string;
                 dbNameRef.value = dbUsersName as string;
                 const version = storageServ?.getDatabaseVersion() as number;

                 const database = await sqliteServ?.openDatabase(
                 dbUsersName,
                 version,
                 false
                 );
                 db.value = database;
                 isDatabase.value = true;
             } catch (error) {
                 const msg = `Error open database: ${error}`;
                 console.error(msg);
                 Toast.show({
                     text: msg,
                     duration: 'long',
                 });
             }
         };

         const handleAddUser = async (newUser: User) =&gt; {
             // Store the new user in the database
             if (db.value) {
                 const isConn = await sqliteServ?.isConnection(dbNameRef.value, false);
                 if (!isConn) {
                     const msg = 'Error handleAddUser: No DatabaseConnection';
                     console.error(msg);
                     Toast.show({
                         text: msg,
                         duration: 'long',
                     });
                 }
                 const lastId = await storageServ?.addUser(newUser);
                 newUser.id = lastId as number;
                 users.value.push(newUser as never);
             }
         };

         const handleUpdateUser = async (updateUser: User) =&gt; {
             // Store the updated user data in the database
             if (db.value) {
                 const isConn = await sqliteServ?.isConnection(dbNameRef.value, false);
                 if (!isConn) {
                     const msg = 'Error handleAddUser: No DatabaseConnection';
                     console.error(msg);
                     Toast.show({
                         text: msg,
                         duration: 'long',
                     });
                 }
                 await storageServ?.replaceUser(updateUser);
                 users.value = users.value.map((user) =&gt; {
                     if (user.id === updateUser.id) {
                         return { ...updateUser };
                     } else {
                         return user;
                     }
                 });
                 centeredModalOpen.value = false;
             }
         };

         const handleUpdateUserActive = async (updUser: User) =&gt; {
             // Store the updated user's active field in the database
             if (db.value) {
                 const isConn = await sqliteServ?.isConnection(dbNameRef.value, false);
                 if (!isConn) {
                     const msg = 'Error handleUpdateUser: No DatabaseConnection';
                     console.error(msg);
                     Toast.show({
                         text: msg,
                         duration: 'long',
                     });
                 }
                 await storageServ?.updateUserActiveById(
                     updUser.id.toString(),
                     updUser.active
                 );
                 users.value = users.value.map((user: User) =&gt; {
                     if (user.id === updUser.id) {
                         // Clone the user and update the active property
                         return { ...user, active: updUser.active };
                     } else {
                         return user;
                     }
                 });
             }
         };

         const handleDeleteUser = async (userId: number) =&gt; {
             // Delete a user from the database by using the id field
             if (db.value) {
                 const isConn = await sqliteServ?.isConnection(dbNameRef.value, false);
                 if (!isConn) {
                     const msg = 'Error handleDeleteUser: No DatabaseConnection';
                     console.error(msg);
                     Toast.show({
                         text: msg,
                         duration: 'long',
                     });
                 }
                 await storageServ?.deleteUserById(userId.toString());
                 users.value = users.value.filter(
                 (user) =&gt; (user as User).id !== userId
                 );
             }
         };

         const handleEditUser = (user: User) =&gt; {
             // Get the user to update and open the modal edit form
             editUser.value = user;
             centeredModalOpen.value = true;
         };

         onMounted(() =&gt; {
             storageServ?.isInitCompleted.subscribe(async (value: boolean) =&gt; {
                 isInitComplete.value = value;
                 // Open the connection to the database
                 if (isInitComplete.value === true) {
                     if (platform === 'web') {
                         // Web Plaform
                         customElements
                         .whenDefined('jeep-sqlite')
                         .then(async () =&gt; {
                             await openDatabase();
                         })
                         .catch((error) =&gt; {
                             const msg = `Error open database: ${error}`;
                             console.log(msg);
                             Toast.show({
                                 text: msg,
                                 duration: 'long',
                             });
                         });
                     } else {
                         // Native Platforms
                         await openDatabase();
                     }
                 }
             });
         });

         onBeforeUnmount(() =&gt; {
         // Close the connection to the database
         sqliteServ
             ?.closeDatabase(dbNameRef.value, false)
             .then(() =&gt; {
                 isDatabase.value = false;
             })
             // eslint-disable-next-line @typescript-eslint/no-explicit-any
             .catch((error: any) =&gt; {
                 const msg = `Error close database:
                             ${error.message ? error.message : error}`;
                 console.error(msg);
                 Toast.show({
                     text: msg,
                     duration: 'long',
                 });
             });
         });

         watch(isDatabase, (newIsDatabase) =&gt; {
             if (newIsDatabase) {
                 // Get all users from the database
                 getAllUsers(db.value as SQLiteDBConnection)
                 // eslint-disable-next-line @typescript-eslint/no-explicit-any
                 .catch((error: any) =&gt; {
                     const msg = `close database:
                                 ${error.message ? error.message : error}`;
                     console.error(msg);
                     Toast.show({
                     text: msg,
                     duration: 'long',
                     });
                 });
             } else {
                 const msg = 'newDb is null';
                 console.error(msg);
                 Toast.show({
                 text: msg,
                 duration: 'long',
                 });
             }
         });

         return {
             centeredModalMarginTop,
             centeredModalOpen,
             dbInitialized,
             editUser,
             isInitComplete,
             users,
             handleAddUser,
             handleDeleteUser,
             handleEditUser,
             handleUpdateUser,
             handleUpdateUserActive,
         };
     },
 });
 &lt;/script&gt;
</code></pre>
  </li>
  <li>
    <p>Create a route for that page in the <code>routes.ts</code> file in the router folder.</p>
  </li>
</ul>

<pre><code class="language-ts">    const routes: RouteRecordRaw[] = [
    {
        path: '/',
        component: () =&gt; import('layouts/MainLayout.vue'),
        children: [
            {
                path: '',
                name: 'home',
                component: () =&gt; import('pages/IndexPage.vue'),
                meta: { title: 'Quasar SQLite App' },
            },
            {
                path: '/users',
                name: 'users',
                component: () =&gt; import('pages/UsersPage.vue'),
                meta: { title: 'Managing Users' },
            },
        ],
    }, 
</code></pre>

<h3 id="users-component-implementation">Users Component Implementation</h3>

<p>In that tutorial we use a simple UI interface for CRUD operations through the use of a <code>UserForm</code> and a <code>UserList</code> components.</p>

<ul>
  <li>
    <p>Under <code>src/components</code> folder create two new files <code>UserForm.vue</code> and <code>UserList.vue</code>.</p>
  </li>
  <li>
    <p>Open the <code>components/UserForm.vue</code> file and copy the following code</p>

    <pre><code class="language-ts"> &lt;template&gt;
     &lt;q-form @submit.prevent="submitForm"&gt;
         &lt;!-- User Name input --&gt;
         &lt;q-input
         v-model="formData.username"
         label="Rose Miller"
         outlined
         dense
         :rules="[charsRule, twoWordsRule]"
         /&gt;
         &lt;!-- User Email Version 2
         &lt;q-input
         v-model="formData.email"
         label="Email"
         outlined
         dense
         :rules="[emailRule]"
         /&gt;
         --&gt;
         &lt;!-- Add more input fields as needed --&gt;

         &lt;q-btn v-if="isFormValid" type="submit" label="Submit" color="primary" /&gt;
     &lt;/q-form&gt;
 &lt;/template&gt;

 &lt;script lang="ts"&gt;
 import { defineComponent, ref } from 'vue';
 import { User } from '../models/User';

 export default defineComponent({
     name: 'UserForm',
     props: {
         method: {
             type: String,
             required: true,
             validator: (value: string) =&gt; {
                 return ['add', 'update'].includes(value);
             },
         },
         user: {
             type: Object as () =&gt; User | null,
             default: null,
         },
         onAddUser: {
             type: Function,
             default: null,
         },
         onUpdateUser: {
             type: Function,
             default: null,
         },
     },
     setup(props) {
         const isFormValid = ref(false);
         const isFormInit = ref(false);
         const formData = ref({
             username: '',
             /* email: '', // version 2 */
         });
         if (props.method === 'update' &amp;&amp; props.onUpdateUser &amp;&amp; props.user) {
             formData.value.username = props.user.name;
             /* formData.value.email = props.user.email; // version 2 */
         }
         /* const emailRule = () =&gt; {
             if (isFormInit.value) return true;
             const isValid = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/.test(formData.value.email);
             return isValid || 'Invalid email format';
         } // version 2 */
         const charsRule = () =&gt; {
             if (isFormInit.value) return true;
             const isValid = /^[a-zA-Z0-9-' ']+$/.test(formData.value.username);
             return isValid || 'Only alphanumeric characters are allowed';
         };
         const twoWordsRule = () =&gt; {
             if (isFormInit.value) return true;
             const words = formData.value.username.trim().split(' ');
             const isValid = words.length &gt;= 2 &amp;&amp; words.every((word) =&gt; word !== '');
             return isValid || 'Must have at least 2 words';
         };
         const submitForm = () =&gt; {
             if (isFormValid.value) {
                 if (props.method === 'add' &amp;&amp; props.onAddUser) {
                     const newUser = {
                         id: Date.now(), // do not care about the id value (generated by sqlite)
                         name: formData.value.username,
                         active: 1,
                         /* email: formData.value.email, // version 2 */
                     };
                     if (typeof props.onAddUser === 'function') {
                         props.onAddUser(newUser);
                     }
                 } else if (
                     props.method === 'update' &amp;&amp;
                     props.onUpdateUser &amp;&amp;
                     props.user
                 ) {
                     const updateUser = {
                         id: props.user.id,
                         name: formData.value.username,
                         active: props.user.active,
                         /* email: formData.value.email, // version 2 */
                     };
                     if (typeof props.onUpdateUser === 'function') {
                         props.onUpdateUser(updateUser);
                     }
                 }
                 formData.value.username = '';
                 /* formData.value.email = ''; // version 2 */
                 isFormInit.value = true;
                 isFormValid.value = false;
             }
         };
         return {
             formData,
             charsRule,
             twoWordsRule,
             submitForm,
             isFormValid,
             /* emailRule, // Version 2 */
         };
     },
 });
 &lt;/script&gt;
</code></pre>
  </li>
  <li>
    <p>Open the <code>components/UserList.vue</code> file and copy the following code</p>

    <pre><code class="language-ts"> &lt;template&gt;
     &lt;q-list&gt;
         &lt;q-item v-for="user in users" :key="user.id"&gt;
         &lt;q-item-section side middle&gt;
             &lt;q-checkbox
             :model-value="userActiveState(user)"
             dense
             @click="handleCheckboxClick(user)"
             /&gt;
         &lt;/q-item-section&gt;
         &lt;q-item-section&gt;
             &lt;q-item-label&gt;  -  &lt;/q-item-label&gt;
             &lt;!-- &lt;q-item-label&gt;  &lt;/q-item-label&gt; // version 2 --&gt;
         &lt;/q-item-section&gt;
         &lt;q-item-section side middle&gt;
             &lt;q-btn
             dense
             flat
             icon="edit"
             color="positive"
             @click="handleEditClick(user)"
             /&gt;
         &lt;/q-item-section&gt;

         &lt;!-- Delete Button with Trash Icon --&gt;
         &lt;q-item-section side middle&gt;
             &lt;q-btn
             dense
             flat
             icon="delete"
             color="negative"
             @click="handleDeleteClick(user.id)"
             /&gt;
         &lt;/q-item-section&gt;
         &lt;/q-item&gt;
     &lt;/q-list&gt;
 &lt;/template&gt;
 &lt;script lang="ts"&gt;
 import { defineComponent } from 'vue';
 import { User } from '../models/User';

 export default defineComponent({
     name: 'UserList',
     props: {
         users: Array as () =&gt; User[],
         onUpdateUserActive: Function,
         onDeleteUser: Function,
         onEditUser: Function,
     },
     setup(props) {
         const userActiveState = (user: User) =&gt; {
         // Convert user.active to boolean
         return user.active === 1;
         };
         const handleCheckboxClick = (user: User) =&gt; {
             // Create a new user object with the updated active value
             const updatedUser = { ...user, active: user.active === 1 ? 0 : 1 };
             if (typeof props.onUpdateUserActive === 'function') {
                     props.onUpdateUserActive(updatedUser);
             }
         };
         const handleDeleteClick = (userId: number) =&gt; {
             if (typeof props.onDeleteUser === 'function') {
                 props.onDeleteUser(userId);
             }
         };
         const handleEditClick = (user: User) =&gt; {
             if (typeof props.onEditUser === 'function') {
                 props.onEditUser(user);
             }
         };

         return {
             userActiveState,
             handleCheckboxClick,
             handleDeleteClick,
             handleEditClick,
         };
     },
 });
 &lt;/script&gt;
</code></pre>

    <p>!!! Caution Between the <q-item-label> &lt;/q-item-label tags
 You must read `Double left Curly Bracket` user.id `Double Right Curly Bracket` - `Double left Curly Bracket` user.name `Double Right Curly Bracket`</q-item-label></p>
  </li>
</ul>

<h3 id="create-the-querysqlite-hook">Create the QuerySQLite Hook</h3>

<p>The Querysqlite hook is a generic query to query date from a database.</p>

<ul>
  <li>Create a <code>hooks</code>folder under <code>src</code> folder.</li>
  <li>
    <p>Create a <code>useQuerySQLite.ts</code> file under the <code>src/hooks</code>folder and copy the below code in it.</p>

    <pre><code class="language-ts"> import { SQLiteDBConnection } from '@capacitor-community/sqlite';

 export const useQuerySQLite = async (
     db: SQLiteDBConnection,
     stmt: string,
     values: never[]
 ) =&gt; {
     if (db) {
         try {
             const queryResult = await db.query(stmt, values);
             return queryResult.values as never[];
         // eslint-disable-next-line @typescript-eslint/no-explicit-any
         } catch (err: any) {
             const msg = err.message ? err.message : err;
             throw new Error(`useQuerySQLite: ${msg}`);
         }
     }
     return [];
 };

</code></pre>
  </li>
</ul>

<h3 id="update-config">Update Config</h3>

<ul>
  <li>For Web application only the appID of the <code>capacitor.config.ts</code> must be amended with <code>YOUR_APP_ID</code></li>
</ul>

<h3 id="run-the-web-sqlite-app">Run the Web SQLite App</h3>

<ul>
  <li>
    <p>To run the Web app use the below command</p>

    <pre><code class="language-bash"> npm run dev
</code></pre>

    <p>When complete successfuly, the app will open in your default browser at</p>

    <pre><code> http://localhost:9000/
</code></pre>
  </li>
  <li>
    <p>This will bring you to the <code>Home</code> page. The video demonstrates the use of the application</p>

    <video width="50%" controls="">
   <source src="/videos/Part-1-Quasar-SQLite-App.mov" type="video/mp4" />
 </video>
    <p><br /></p>
  </li>
</ul>

<h3 id="video-storyboard">Video storyboard</h3>

<pre><code>- &lt;p&gt;To open the menu, click on the &lt;span style="font-size: 24px;"&gt;&lt;ion-icon name="menu"&gt;&lt;/ion-icon&gt;&lt;/span&gt; icon in the top right corner.&lt;/p&gt;

- &lt;p&gt; In the &lt;strong&gt;&lt;code&gt;Menu Content&lt;/code&gt;&lt;/strong&gt; click on &lt;strong&gt;&lt;code&gt;Managing Users&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
 
- &lt;p&gt; Enter a new user name (Sue Hellen) on the input field &lt;strong&gt;&lt;code&gt;Rose Miller&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

- &lt;p&gt; Click on the &lt;strong&gt;&lt;code&gt;SUBMIT&lt;/code&gt;&lt;/strong&gt; button&lt;/p&gt;

- &lt;p&gt;&lt;strong&gt;&lt;code&gt;Sue Hellen&lt;/code&gt;&lt;/strong&gt;is now added to the Current Users list &lt;/p&gt;

- &lt;p&gt; Enter a new user name (Dave Wat) on the input field &lt;strong&gt;&lt;code&gt;Rose Miller&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

- &lt;p&gt; Click on the &lt;strong&gt;&lt;code&gt;SUBMIT&lt;/code&gt;&lt;/strong&gt; button&lt;/p&gt;

- &lt;p&gt;&lt;strong&gt;&lt;code&gt;Dave Wat&lt;/code&gt;&lt;/strong&gt; is now added to the Current Users list &lt;/p&gt;

- &lt;p&gt; Update the &lt;strong&gt;&lt;code&gt;active&lt;/code&gt;&lt;/strong&gt; value for a user by pressing on the check icon on the left it will toggle the value from 1 to 0&lt;/p&gt;

- &lt;p&gt; Modify the name &lt;strong&gt;&lt;code&gt;Dave Wat&lt;/code&gt;&lt;/strong&gt; by clicking on the &lt;span style="font-size: 24px;color: #21BA45;"&gt;&lt;ion-icon name="pencil"&gt;&lt;/ion-icon&gt;&lt;/span&gt; icon&lt;/p&gt;

- &lt;p&gt;The &lt;strong&gt;&lt;code&gt;Update User&lt;/code&gt;&lt;/strong&gt; modal form appears and update the name &lt;strong&gt;&lt;code&gt;Dave Watson&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;.

- &lt;p&gt; Click on the &lt;strong&gt;&lt;code&gt;SUBMIT&lt;/code&gt;&lt;/strong&gt; button, the modal form disappears and the &lt;strong&gt;&lt;code&gt;Current Users&lt;/code&gt;&lt;/strong&gt; list is updated&lt;/p&gt;

- &lt;p&gt; Enter a new user name (James Dean) on the input field &lt;strong&gt;&lt;code&gt;Rose Miller&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

- &lt;p&gt; Click on the &lt;strong&gt;&lt;code&gt;SUBMIT&lt;/code&gt;&lt;/strong&gt; button&lt;/p&gt;

- &lt;p&gt;&lt;strong&gt;&lt;code&gt;James Dean&lt;/code&gt;&lt;/strong&gt; is now added to the Current Users list &lt;/p&gt;

-&lt;p&gt; Delete the user &lt;strong&gt;&lt;code&gt;James Dean&lt;/code&gt;&lt;/strong&gt; by clicking on the &lt;span style="font-size: 24px;color: #C10015;"&gt;&lt;ion-icon name="trash"&gt;&lt;/ion-icon&gt;&lt;/span&gt;&lt;/p&gt; icon

-&lt;p&gt; Click on the &lt;strong&gt;&lt;code&gt;Back&lt;/code&gt;&lt;/strong&gt; button will route you back to the &lt;strong&gt;&lt;code&gt;Home&lt;/code&gt;&lt;/strong&gt; page &lt;/p&gt; and save the database to store.
</code></pre>

<p>The database location can be see in the application tab of the development tools.</p>

<div align="center"><br /><img src="/images/Ionic7-Vue-SQLite-Database-Location.png" width="80%" /></div>
<p><br /></p>

<h3 id="upgrade-database-to-version-2">Upgrade Database to Version 2</h3>

<p>To upgrade the database to version 2, incremental upgrade statements will be used.
An <code>email</code> field is added to the users table in version 2.</p>

<p>The initial application code contains the code, but it has been accompanied by comments using the symbols ‘/<em>’ and ‘</em>/’. These symbols require removal.</p>

<ul>
  <li>Open the file <code>user.statements.ts</code> in folder <code>src/upgrades</code> and remove the symbols.</li>
</ul>

<pre><code class="language-ts">    export const UserUpgradeStatements = [
        {
            toVersion: 1,
            statements: [
            `CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            active INTEGER DEFAULT 1
            );`,
            ],
        },
        /* add new statements below for next database version when required*/
        {
            toVersion: 2,
            statements: ['ALTER TABLE users ADD COLUMN email TEXT;'],
        },
    ];
</code></pre>

<ul>
  <li>The <code>user</code> model requires removal of symbols. Open the file <code>User.ts</code> in the <code>src/models</code> folder.</li>
</ul>

<pre><code class="language-ts">    export interface User {
        id: number;
        name: string;
        active: number;
        email: string; // Version 2
    }
</code></pre>

<ul>
  <li>The addition of an email input field affects the <code>UserForm</code> component. Open the file <code>UserForm.vue</code> in the folder <code>src/components</code>.</li>
</ul>

<pre><code class="language-ts">    &lt;template&gt;
        &lt;q-form @submit.prevent="submitForm"&gt;
            &lt;!-- User Name input --&gt;
            &lt;q-input
                v-model="formData.username"
                label="Rose Miller"
                outlined
                dense
                :rules="[charsRule, twoWordsRule]"
            /&gt;
            &lt;!-- User Email Version 2 --&gt;
            &lt;q-input
                v-model="formData.email"
                label="Email"
                outlined
                dense
                :rules="[emailRule]"
            /&gt;
            &lt;!-- Add more input fields as needed --&gt;

            &lt;q-btn v-if="isFormValid" type="submit" label="Submit" color="primary" /&gt;
        &lt;/q-form&gt;
    &lt;/template&gt;

    &lt;script lang="ts"&gt;
    import { defineComponent, ref } from 'vue';
    import { User } from '../models/User';

    export default defineComponent({
        name: 'UserForm',
        props: {
            method: {
                type: String,
                required: true,
                validator: (value: string) =&gt; {
                    return ['add', 'update'].includes(value);
                },
            },
            user: {
                type: Object as () =&gt; User | null,
                default: null,
            },
            onAddUser: {
                type: Function,
                default: null,
            },
            onUpdateUser: {
                type: Function,
                default: null,
            },
        },
        setup(props) {
            const isFormValid = ref(false);
            const isFormInit = ref(false);
            const formData = ref({
                username: '',
                email: '', // version 2
            });
            if (props.method === 'update' &amp;&amp; props.onUpdateUser &amp;&amp; props.user) {
                formData.value.username = props.user.name;
                formData.value.email = props.user.email; // version 2
            }
            const emailRule = () =&gt; {
                if (isFormInit.value) return true;
                const isValid = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/.test(
                    formData.value.email
                );
                return isValid || 'Invalid email format';
            }; // version 2
            const charsRule = () =&gt; {
                if (isFormInit.value) return true;
                const isValid = /^[a-zA-Z0-9-' ']+$/.test(formData.value.username);
                return isValid || 'Only alphanumeric characters are allowed';
            };
            const twoWordsRule = () =&gt; {
                if (isFormInit.value) return true;
                const words = formData.value.username.trim().split(' ');
                const isValid = words.length &gt;= 2 &amp;&amp; words.every((word) =&gt; word !== '');
                return isValid || 'Must have at least 2 words';
            };
            const handleEnterKey = (event: { preventDefault: () =&gt; void }) =&gt; {
                if (isFormInit.value) {
                    isFormInit.value = false;
                    event.preventDefault();
                }
                // Check all rules and update isFormValid
                isFormValid.value =
                    charsRule() === true &amp;&amp; twoWordsRule() === true &amp;&amp; emailRule() === true; // version 2

                if (!isFormValid.value) {
                    // Prevent form submission on Enter key if the form is not valid
                    event.preventDefault();
                }
            };
            const submitForm = () =&gt; {
                if (isFormValid.value) {
                    if (props.method === 'add' &amp;&amp; props.onAddUser) {
                        const newUser = {
                            id: Date.now(), // do not care about the id value (generated by sqlite)
                            name: formData.value.username,
                            active: 1,
                            email: formData.value.email, // version 2
                        };
                        if (typeof props.onAddUser === 'function') {
                            props.onAddUser(newUser);
                        }
                    } else if (
                    props.method === 'update' &amp;&amp;
                    props.onUpdateUser &amp;&amp;
                    props.user
                    )   {
                        const updateUser = {
                            id: props.user.id,
                            name: formData.value.username,
                            active: props.user.active,
                            email: formData.value.email, // version 2
                        };
                        if (typeof props.onUpdateUser === 'function') {
                            props.onUpdateUser(updateUser);
                        }
                    }
                    formData.value.username = '';
                    formData.value.email = ''; // version 2
                    isFormInit.value = true;
                    isFormValid.value = false;
                }
            };
            return {
                formData,
                charsRule,
                twoWordsRule,
                submitForm,
                isFormValid,
                emailRule, // Version 2
            };
        },
    });
    &lt;/script&gt;
</code></pre>

<ul>
  <li>
    <p>It also affects the <code>UserList</code> component as the email must be displayed. Open the file <code>UserList.vue</code> in the folder <code>src/components</code>.
 The <code>&lt;!-- &lt;q-item-label&gt;  &lt;/q-item-label&gt; // version 2 --&gt;</code>
 must be uncommented  like this <code>&lt;q-item-label&gt;  &lt;/q-item-label&gt;</code>.</p>
  </li>
  <li>
    <p>run the application</p>

    <pre><code class="language-bash"> npm run dev
</code></pre>
    <p>When complete successfuly, the app will open in your default browser at</p>

    <pre><code> http://localhost:9000/
</code></pre>
  </li>
  <li>
    <p>This will bring you to the <code>Home</code> page. The video demonstrates the use of the application for the database version 2</p>

    <video width="50%" controls="">
   <source src="/videos/Part-1-Quasar-SQLite-App2.mov" type="video/mp4" />
 </video>
    <p><br /></p>
  </li>
  <li>
    <p>Video storyboard</p>

    <ul>
      <li>
        <p>To open the menu, click on the <span style="font-size: 24px;"><ion-icon name="menu"></ion-icon></span> icon in the top right corner.</p>
      </li>
      <li>
        <p> In the <strong><code>Menu Content</code></strong> click on <strong><code>Managing Users</code></strong></p>
      </li>
      <li>
        <p> The <strong><code>email</code></strong> input field has been added to the <strong><code>Add New User</code></strong> form.</p>
      </li>
      <li>
        <p> The <strong><code>Current Users</code></strong> list shows the existing users</p>
      </li>
      <li>
        <p> Add the new user <strong><code>James Dean</code></strong> and its email <strong><code>james.dean@example.com</code></strong></p>
        <p>.</p>
      </li>
      <li>
        <p> Click on the <strong><code>SUBMIT</code></strong> button. Check that the user list is updated.</p>
      </li>
      <li>
        <p> Update the email for <strong><code>Sue Hellen</code></strong> user by clicking on the <span style="font-size: 24px;color: #21BA45;"><ion-icon name="pencil"></ion-icon></span> icon</p>
      </li>
      <li>
        <p>The <strong><code>Update User</code></strong> modal form appears and update the email <strong><code>sue.hellen@example.com</code></strong></p>
        <p>.</p>
      </li>
      <li>
        <p> Click on the <strong><code>SUBMIT</code></strong> button. Check that the user list is updated.</p>
      </li>
      <li>
        <p> Update the email for <strong><code>Dave Watson</code></strong> user by clicking on the <span style="font-size: 24px;color: #21BA45;"><ion-icon name="pencil"></ion-icon></span> icon</p>
      </li>
      <li>
        <p>The <strong><code>Update User</code></strong> modal form appears and update the email <strong><code>dave.watson@example.com</code></strong></p>
        <p>.</p>
      </li>
      <li>
        <p> Click on the <strong><code>SUBMIT</code></strong> button. Check that the user list is updated.</p>
      </li>
      <li>
        <p> The database <strong><code>Version 2</code></strong> is now fully updated.</p>
      </li>
    </ul>
  </li>
</ul>

<h3 id="part-1-conclusion">Part 1 Conclusion</h3>

<p>We have completed the Part 1 - Web application of the Quasar SQLite Database CRUD App Example Tutorial using Quasar Framework and @capacitor-community/sqlite.</p>

<p>We learned how to implement the ‘@capacitor-community/sqlite’ plugin in the Quasar Framework on a Web platform.</p>

<p>We learned to use <code>provide/inject</code> to ensure that the services are unique and available to all components within the app.</p>

<p>We learned how to create an application menu.</p>

<p>We learned how to used some basic methods of the ‘@capacitor-community/sqlite’ plugin to create a CRUD application from scratched and store persistent SQLite data into the Web IndexedDB browser database.</p>

<p>We learned how to upgrade the <code>version</code> of the database by using the incremental upgrade statements process.</p>

<p>Enjoy your development from there.</p>

<h2 id="part-2---native---table-of-contents">Part 2 - Native - Table of Contents</h2>

<hr />
<ul>
  <li><a href="#update-capacitor-config-file">Update Capacitor Config file</a></li>
  <li><a href="#install-native-required-packages">Install Native Required Packages</a></li>
  <li><a href="#update-packagejson-scripts">Update Package.json Scripts</a></li>
  <li><a href="#run-the-ios-app">Run the iOS App</a></li>
  <li><a href="#run-the-android-app">Run the Android App</a></li>
  <li><a href="#run-the-electron-app">Run the Electron App</a></li>
  <li><a href="#part-2-conclusion">Part 2 Conclusion</a></li>
</ul>

<hr />

<h3 id="update-capacitor-config-file">Update Capacitor Config file</h3>

<p>The <code>capacitor.config.ts</code> file specifies parameters that the plugin needs, such as database location, database encryption, and the use of biometric authentication for access security. Such settings may be platform specific.</p>

<p>CAUTION: Make sure that the <code>webDir</code> is set to <code>dist/spa</code>.</p>

<ul>
  <li>
    <p>Please modify the <code>capacitor.config.ts</code> file as below :</p>

    <pre><code class="language-ts"> import { CapacitorConfig } from '@capacitor/cli';

 const config: CapacitorConfig = {
 appId: 'YOUR_APP_ID',
 appName: 'YOUR_APP_NAME',
 webDir: 'dist/spa',
 loggingBehavior: 'debug',
 server: {
     androidScheme: "http"
 },
 plugins: {
     CapacitorSQLite: {
     iosDatabaseLocation: 'Library/CapacitorDatabase',
     iosIsEncryption: false,
     iosKeychainPrefix: 'YOUR_APP_NAME',
     iosBiometric: {
         biometricAuth: false,
         biometricTitle : "Biometric login for capacitor sqlite"
     },
     androidIsEncryption: false,
     androidBiometric: {
         biometricAuth : false,
         biometricTitle : "Biometric login for capacitor sqlite",
         biometricSubTitle : "Log in using your biometric"
     },
     electronIsEncryption: false,
     electronWindowsLocation: "C:\\ProgramData\\CapacitorDatabases",
     electronMacLocation: "/Users/YOUR_NAME/CapacitorDatabases",
     electronLinuxLocation: "Databases"
     }
 }
 };
 export default config;
</code></pre>
  </li>
</ul>

<h3 id="install-native-required-packages">Install Native Required Packages</h3>

<ul>
  <li>
    <p>In order to build Android, iOS, or Electron applications on specific devices, it is necessary to install the necessary capacitor packages first. So run the following commands:</p>

    <pre><code class="language-bash"> npm i @capacitor/android
 npm i @capacitor/ios
 npm i @capacitor-community/electron
 npm i -D rimraf
</code></pre>
  </li>
  <li>
    <p>Integrate the various platforms into the application.</p>

    <pre><code class="language-bash"> npm run build
 npx cap add android
 npx cap add ios
 npx cap add @capacitor-community/electron
</code></pre>
  </li>
</ul>

<h3 id="update-packagejson-scripts">Update Package.json Scripts</h3>

<ul>
  <li>
    <p>First install a new package to remove the sql.js wasm file to reduce the native package size</p>

    <pre><code class="language-bash"> npm install -D rimraf
</code></pre>
  </li>
  <li>
    <p>Open the <code>package.json</code> file and replace the scripts section with:</p>

    <pre><code class="language-json"> "scripts": {
     "lint": "eslint --ext .js,.ts,.vue ./",
     "format": "prettier --write \"**/*.{js,ts,vue,css,html,md,json}\" --ignore-path .gitignore",
     "test": "echo \"No test specified\" &amp;&amp; exit 0",
     "dev": "npm run copy:sql:wasm &amp;&amp; quasar dev",
     "build": "quasar build",
     "build:web": "npm run copy:sql:wasm &amp;&amp; quasar build",
     "build:native": "npm run remove:sql:wasm &amp;&amp; quasar build",
     "copy:sql:wasm": "copyfiles -u 3 node_modules/sql.js/dist/sql-wasm.wasm public/assets",
     "remove:sql:wasm": "rimraf public/assets/sql-wasm.wasm",
     "ios:start": "npm run build:native &amp;&amp; npx cap sync &amp;&amp; npx cap copy &amp;&amp; npx cap open ios",
     "android:start": "npm run build:native &amp;&amp; npx cap sync &amp;&amp; npx cap copy &amp;&amp; npx cap open android",
     "electron:install": "cd electron &amp;&amp; npm install &amp;&amp; cd ..",
     "electron:prepare": "npm run build:native &amp;&amp; npx cap sync @capacitor-community/electron &amp;&amp; npx cap copy @capacitor-community/electron",
     "electron:start": "npm run electron:prepare &amp;&amp; cd electron &amp;&amp; npm run electron:start"
 },
</code></pre>
  </li>
</ul>

<h3 id="run-the-ios-app">Run the iOS App</h3>

<ul>
  <li>
    <p>Before running on iOS, the code has to be modified to account for the difference between the <code>Super View</code> and the <code>Safe Area</code>.</p>

    <ul>
      <li>Open the <code>app.css</code> file under the <code>src/css</code> folder and add:</li>
    </ul>

    <pre><code class="language-css"> .ios {
     top: 44px;
 }
</code></pre>

    <ul>
      <li>Change the code in file `src/pages/IndexPage.vue&gt; to match this one.</li>
    </ul>

    <pre><code class="language-ts"> &lt;template&gt;
     &lt;q-page&gt;
         &lt;app-logo&gt;&lt;/app-logo&gt;
         &lt;app-intro-text&gt;&lt;/app-intro-text&gt;
     &lt;/q-page&gt;
 &lt;/template&gt;

 &lt;script lang="ts"&gt;
 import { defineComponent, onMounted, inject } from 'vue';
 import AppLogo from 'components/AppLogo.vue';
 import AppIntroText from 'components/AppIntroText.vue';
 import SQLiteService from 'src/services/sqliteService';

 export default defineComponent({
 name: 'IndexPage',
 components: { AppLogo, AppIntroText },
     setup() {
         // Inject services
         const sqliteServ: SQLiteService | undefined = inject('sqliteServ');
         const platform = sqliteServ?.getPlatform();
         onMounted(() =&gt; {
             if (platform === 'ios') {
                 const headerEl = document.querySelector('.q-header');
                 headerEl?.classList.add('ios');
                 const pageEl = document.querySelector('.q-page');
                 pageEl?.classList.add('ios');
             }
         });
         return {};
     },
 });
 &lt;/script&gt;
</code></pre>
    <ul>
      <li>Change the unMounted method code in file `src/pages/UsersPage.vue&gt; to match this one.</li>
    </ul>

    <pre><code class="language-ts"> onMounted(() =&gt; {
   if (platform === 'ios') {
     const headerEl = document.querySelector('.q-header');
     headerEl?.classList.add('ios');
     const pageEl = document.querySelector('.q-page');
     pageEl?.classList.add('ios');
   }
   storageServ?.isInitCompleted.subscribe(async (value: boolean) =&gt; {
     isInitComplete.value = value;
     // Open the connection to the database
     if (isInitComplete.value === true) {
       if (platform === 'web') {
         // Web Plaform
         customElements
           .whenDefined('jeep-sqlite')
           .then(async () =&gt; {
             await openDatabase();
           })
           .catch((error) =&gt; {
             const msg = `Error open database: ${error}`;
             console.log(msg);
             Toast.show({
               text: msg,
               duration: 'long',
             });
           });
       } else {
         // Native Platforms
         await openDatabase();
       }
     }
   });
 });
</code></pre>
  </li>
  <li>
    <p>Open the file `src/layouts/MainLayout.vue&gt; to match this one.</p>

    <ul>
      <li>add in the <code>import</code> section</li>
    </ul>

    <pre><code class="language-ts"> import { Capacitor } from '@capacitor/core';
</code></pre>

    <ul>
      <li>modify the <code>setup</code> method</li>
    </ul>

    <p>```ts
 setup() {
     const rightDrawerOpen = ref(false);
     const platform = Capacitor.getPlatform();
     return {
         pages: pageList,
         rightDrawerOpen,
         toggleRightDrawer() {
             rightDrawerOpen.value = !rightDrawerOpen.value;
             if (platform === ‘ios’) {
                 // eslint-disable-next-line @typescript-eslint/no-explicit-any
                 const menuEl: any = document.querySelector(‘.q-drawer’);
                 menuEl.style.top = ‘44px’;
             }
         },
     };
 },</p>
  </li>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> npm run ios:start
</code></pre>
  </li>
  <li>
    <p>In Xcode wait for indexed file to complete, clean the project and run the app.</p>
  </li>
  <li>
    <p>This will bring you to the <code>Home</code> page. The video demonstrates the use of the application for the database version 1</p>

    <video width="50%" controls="">
   <source src="/videos/Part-2-iOS-Quasar-SQLite-App.mov" type="video/mp4" />
 </video>
    <p><br /></p>
  </li>
  <li>
    <p>The <code>video storyboard</code> is the same that for the Web Part1 <a href="#video-storyboard">Video Storyboard</a>.</p>
  </li>
</ul>

<h3 id="run-the-android-app">Run the Android App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> npm run android:start
</code></pre>
  </li>
  <li>
    <p>In Android Studio</p>

    <ul>
      <li>go to the menu Android/Preferences/Build, Execution, Deployment/Build Tools/Gradle and then select the gradle JDK <code>17 Oracle OpenJDK Version 17.0.7</code>. Then press <code>Apply</code> and <code>OK</code>.</li>
      <li>go to File/Sync Project With Gradle Files.</li>
      <li>go to Build/Clean Project.</li>
      <li>select your Emulator or Physical Device.</li>
      <li>run the app</li>
    </ul>
  </li>
  <li>
    <p>This will bring you to the <code>Home</code> page. The video demonstrates the use of the application for the database version 1</p>

    <video width="50%" controls="">
   <source src="/videos/Part-2-Android-Quasar-SQLite-App.mov" type="video/mp4" />
 </video>
    <p><br /></p>
  </li>
  <li>
    <p>The <code>video storyboard</code> is the same that for the Web Part1 <a href="#video-storyboard">Video Storyboard</a>.</p>
  </li>
</ul>

<h3 id="run-the-electron-app">Run the Electron App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> cd electron
</code></pre>
  </li>
  <li>
    <p>Open the <code>package.json</code> file and replace the scripts:, dependencies:, devDependencies: sections with:</p>

    <pre><code class="language-json"> "scripts": {
     "build": "tsc &amp;&amp; electron-rebuild",
     "electron:start-live": "node ./live-runner.js",
     "electron:start": "npm run build &amp;&amp;  electron --inspect=5858 ./",
     "electron:pack": "npm run build &amp;&amp; electron-builder build --dir -c ./electron-builder.config.json",
     "electron:make": "npm run build &amp;&amp; electron-builder build -c ./electron-builder.config.json -p always"
 },
 "dependencies": {
     "@capacitor-community/electron": "^5.0.1",
     "@capacitor-community/sqlite": "^5.4.2-2",
     "better-sqlite3-multiple-ciphers": "^9.1.1",
     "chokidar": "~3.5.3",
     "crypto": "^1.0.1",
     "crypto-js": "^4.1.1",
     "electron-is-dev": "~2.0.0",
     "electron-json-storage": "^4.6.0",
     "electron-serve": "~1.2.0",
     "electron-unhandled": "~4.0.1",
     "electron-updater": "^6.1.7",
     "electron-window-state": "^5.0.3",
     "jszip": "^3.10.1",
     "node-fetch": "2.6.7"
 },
 "devDependencies": {
     "@electron/rebuild": "^3.4.0",
     "@types/better-sqlite3": "^7.6.8",
     "@types/crypto-js": "^4.1.1",
     "@types/electron-json-storage": "^4.5.0",
     "electron": "^27.1.3",
     "electron-builder": "^24.9.1",
     "typescript": "^5.0.4"
 },

</code></pre>
  </li>
  <li>
    <p>In your Editor delete the <code>node_modules</code> folder and <code>package-lock.json</code> file.</p>
  </li>
  <li>
    <p>Then run the following commands:</p>

    <pre><code class="language-bash"> npm install
 cd ..
 npm run electron:start
</code></pre>
  </li>
  <li>
    <p>This will bring you to the <code>Home</code> page. The video demonstrates the use of the application for the database version 1</p>

    <video width="50%" controls="">
   <source src="/videos/Part-2-Electron-Quasar-SQLite-App.mov" type="video/mp4" />
 </video>
    <p><br /></p>
  </li>
  <li>
    <p>The <code>video storyboard</code> is the same that for the Web Part1 <a href="#video-storyboard">Video Storyboard</a>.</p>
  </li>
</ul>

<h3 id="part-2-conclusion">Part 2 Conclusion</h3>

<p>We have completed the Part 2 - Native and Electron applications of the Quasar SQLite Database CRUD App Example Tutorial using Quasar Framework and @capacitor-community/sqlite.</p>

<p>We have learned to adapt the <code>capacitor.config.ts</code>file and the modify the scripts: section of the <code>package.json</code>file for native apps</p>

<p>We learned how to modify the code to adapt to the <code>safe area</code>on iOS device.</p>

<p>We learned how to build and run the application for each native platforms.</p>

<p>Enjoy your development from there.</p>]]></content><author><name>Quéau Jean Pierre</name></author><category term="Other" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Ionic 7 VideoPlayer App Example Tutorial using Angular and capacitor-video-player plugin</title><link href="https://jepiqueau.github.io/2023/11/08/Ionic7Angular-VideoPlayer-App.html" rel="alternate" type="text/html" title="Ionic 7 VideoPlayer App Example Tutorial using Angular and capacitor-video-player plugin" /><published>2023-11-08T00:00:00+00:00</published><updated>2023-11-08T00:00:00+00:00</updated><id>https://jepiqueau.github.io/2023/11/08/Ionic7Angular-VideoPlayer-App</id><content type="html" xml:base="https://jepiqueau.github.io/2023/11/08/Ionic7Angular-VideoPlayer-App.html"><![CDATA[<hr />

<p><em>last updated on December 16, 2023 by Quéau Jean Pierre</em></p>

<p>In this tutorial, we will learn how to create a simple Ionic7/Angular video player application by implementing the capacitor-video-player plugin to display a list of videos with some data and play a selected video in fullscreen mode.</p>

<p>By using Ionic Capacitor 5, the application will use a single source code for the creation of web browser, PWA and native (iOS, Android) applications.</p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/Videoplayer/ionic7-angular-videoplayer-app">ionic7-angular-videoplayer-app</a></p>

<h2 id="table-of-contents">Table of Contents</h2>

<hr />
<ul>
  <li><a href="#create-new-ionicangular-application">Create New Ionic/Angular Application</a></li>
  <li><a href="#create-a-data-service">Create a Data Service</a></li>
  <li><a href="#show-the-video-list-on-home-page">Show the Video List on Home Page</a></li>
  <li><a href="#create-the-videoitem-component">Create the videoitem component</a></li>
  <li><a href="#serve-the-application">Serve the Application</a></li>
  <li><a href="#install-the-capacitor-video-player-plugin">Install the Capacitor Video Player Plugin</a></li>
  <li><a href="#create-the-viewvideo-page">Create the Viewvideo Page</a></li>
  <li><a href="#capacitor-video-player-api-methods">Capacitor Video Player API methods</a></li>
  <li><a href="#run-the-web-application">Run the Web Application</a></li>
  <li><a href="#prepare-for-native-applications">Prepare for Native Applications</a></li>
  <li><a href="#run-the-ios-application">Run the iOS Application</a></li>
  <li><a href="#run-the-android-application">Run the Android Application</a></li>
  <li><a href="#how-to-play-local-videos-in-android-and-ios">How to Play Local Videos in Android and iOS</a></li>
  <li><a href="#conclusion">Conclusion</a></li>
</ul>

<h3 id="create-new-ionicangular-application">Create New Ionic/Angular Application</h3>

<ul>
  <li>To create a new Ionic/Angular application, we will use the <code>Ionic CLI</code>. Install it with the following command.</li>
</ul>

<pre><code class="language-bash">    npm install -g @ionic/cli
</code></pre>

<ul>
  <li>After installation, create the new Ionic/Angular application with the following command.</li>
</ul>

<pre><code class="language-bash">    ionic start ionic7-angular-videoplayer-app list --type=angular --capacitor
</code></pre>

<pre><code>Select `Standalone Components` as build method when asked.
</code></pre>

<ul>
  <li>
    <p>When the new application is successfully created it will show a message to serve an application using <code>ionic serve</code>.</p>
  </li>
  <li>
    <p>Go to the newly created application.</p>
  </li>
</ul>

<pre><code class="language-bash">    cd ./ionic7-angular-videoplayer-app
</code></pre>

<ul>
  <li>Open the application in your favorite code editor</li>
</ul>

<h3 id="create-a-data-service">Create a Data Service</h3>

<ul>
  <li>
    <p>if a <code>data.service.ts</code>file exists on the <code>app/services</code>, please update it with the below code. Otherwise create a <code>services</code> folder under the <code>app</code>folder and create a <code>data.service.ts</code> file with your favorite code editor.</p>
  </li>
  <li>
    <p>Then replace/create the code in <code>data.service.ts</code>.</p>
  </li>
</ul>

<pre><code class="language-ts"> import { Injectable } from '@angular/core';

export interface Video {
  device: string;
  type: string;
  title: string;
  url: string;
  thumb?: string;
  note: string;
  subtitle?: string,
  stlang?: string,
}


@Injectable({
  providedIn: 'root'
})
export class DataService {
  private videos: Video[] = [
    {
      type: "mp4",
      device: "all",
      url: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
      note: "By Blender Foundation",
      thumb: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg",
      title: "Big Buck Bunny"
    },
    {
      type: "mp4",
      device: "all",
      url: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4",
      note: "By Blender Foundation",
      thumb: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ElephantsDream.jpg",
      title: "Elephant Dream"
    },
    {
      type: "mp4",
      device: "all",
      url: "https://media.bernat.ch/videos/2019-self-hosted-videos-subtitles/progressive.mp4",
      note: "Blender Animation Studio",
      thumb: "https://d2pzklc15kok91.cloudfront.net/images/posters/2019-self-hosted-videos-subtitles.3b55d44c736235.jpg",
      title: "327",
      subtitle: "https://media.bernat.ch/videos/2019-self-hosted-videos-subtitles.en.vtt",
      stlang: "en"
    },
    {
      type: "aws",
      device: "all",
      url: "https://universo-dev-a-m.s3.amazonaws.com/779970/fe774806dbe7ad042c24ce522b7b46594f16c66e",
      note: "Custom",
      title: "AWS video test",
    },
    {
      type: "hls",
      device: "all",
      url: "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8",
      note: "By Blender Foundation",
      title: "Big Buck Bunny",
    },
    {
      type: "mpd",
      device: "android",
      url: "https://bitmovin-a.akamaihd.net/content/MI201109210084_1/mpds/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.mpd",
      note: "",
      title: "MPD video test",
    },
    {
      type: "ism",
      device: "android",
      url: "https://test.playready.microsoft.com/smoothstreaming/SSWSS720H264/SuperSpeedway_720.ism/manifest",
      note: "",
      title: "ISM video test",
    },
    {
      type: "webm",
      device: "android",
      url: "https://upload.wikimedia.org/wikipedia/commons/transcoded/f/f1/Sintel_movie_4K.webm/Sintel_movie_4K.webm.720p.webm",
      note: "Blender Foundation",
      title: "ISM video test",
    },
  ];

  constructor() { }

  public getVideos(platform: string): Video[] {
    if (platform === 'web') {
      // Filter videos for Web platform (device: 'all')
      return this.videos.filter((video) =&gt; video.device === 'all');
    } else if (platform === 'android') {
      // Filter videos for Android platform (device: 'all' or 'android')
      return this.videos.filter((video) =&gt; video.device === 'all' || video.device === 'android');
    } else if (platform === 'ios') {
      // Filter videos for iOS platform (device: 'all' or 'ios')
      return this.videos.filter((video) =&gt; video.device === 'all' || video.device === 'ios');
    } else {
      return [];
    }
  }
  public getVideo(index:number): Video | null {
    if(index &lt;= this.videos.length) {
      return this.videos[index];
    } else {
      return null;
    }
  }

}
</code></pre>

<ul>
  <li>Suppress the <code>message</code> folder and the <code>view-message</code> folder if they exist.</li>
</ul>

<h3 id="show-the-video-list-on-home-page">Show the Video List on Home Page</h3>

<p>Fetch the Video list from the <code>DataService</code> and render it on the Home page.</p>

<ul>
  <li>Open the <code>home.page.html</code> under the <code>home</code>folder and replace the code with this.</li>
</ul>

<pre><code class="language-html">    &lt;ion-header [translucent]="true"&gt;
        &lt;ion-toolbar&gt;
            &lt;ion-title&gt;
            Video List
            &lt;/ion-title&gt;
        &lt;/ion-toolbar&gt;
    &lt;/ion-header&gt;
    &lt;ion-content [fullscreen]="true"&gt;
        &lt;ion-refresher slot="fixed" (ionRefresh)="refresh($event)"&gt;
            &lt;ion-refresher-content&gt;&lt;/ion-refresher-content&gt;
        &lt;/ion-refresher&gt;
        &lt;ion-header collapse="condense"&gt;
            &lt;ion-toolbar&gt;
            &lt;ion-title size="large"&gt;
                Video List
            &lt;/ion-title&gt;
            &lt;/ion-toolbar&gt;
        &lt;/ion-header&gt;

        &lt;ion-list&gt;
            &lt;app-videoitem *ngFor="let video of getVideos(); index as i" [video]="video" [index]="i"&gt;&lt;/app-videoitem&gt;
        &lt;/ion-list&gt;
    &lt;/ion-content&gt;
</code></pre>

<ul>
  <li>Then open the <code>home.page.ts</code> under the <code>home</code>folder and replace the code with this.</li>
</ul>

<pre><code class="language-ts">    import { CommonModule } from '@angular/common';
    import { Component, inject, AfterViewInit } from '@angular/core';
    import { RefresherCustomEvent, IonHeader, IonToolbar, IonTitle, IonContent, IonRefresher, IonRefresherContent, IonList } from '@ionic/angular/standalone';
    import { VideoitemComponent } from '../components/videoitem/videoitem.component';
    import { DataService, Video} from '../services/data.service';
    import { Device } from '@capacitor/device';

    @Component({
        selector: 'app-home',
        templateUrl: 'home.page.html',
        styleUrls: ['home.page.scss'],
        standalone: true,
        imports: [CommonModule, IonHeader, IonToolbar, IonTitle, IonContent, IonRefresher, IonRefresherContent, IonList, VideoitemComponent],
    })
    export class HomePage implements AfterViewInit {
        public platform: string = 'web';
        private data = inject(DataService);


        constructor() {}

        async ngAfterViewInit() {
            const info = await Device.getInfo();
            this.platform = info.platform;
            console.log(`*** in home platform: ${this.platform}`);

        }


        refresh(ev: any) {
            setTimeout(() =&gt; {
            (ev as RefresherCustomEvent).detail.complete();
            }, 3000);
        }

        getVideos(): Video[] {
            return this.data.getVideos(this.platform);
        }
    }
</code></pre>

<p>as you saw in the code we need to define a <code>Videoitem</code> component to render a Video element.</p>

<h3 id="create-the-videoitem-component">Create the Videoitem Component</h3>

<ul>
  <li>For the creation of the <code>Videoitem</code> component we will use the <code>Ionic CLI</code>.</li>
</ul>

<pre><code class="language-bash">    ionic generate component components/videoitem 
</code></pre>

<ul>
  <li>When the <code>Videoitem</code>has been successfully generated, open the <code>videoitem.component.html</code> file in your favorite code editor and replace the code.</li>
</ul>

<pre><code class="language-html">    &lt;ion-item&gt;
    &lt;ion-avatar slot="start"&gt;
        &lt;img [src]="video!.thumb" /&gt;
    &lt;/ion-avatar&gt;
    &lt;div class="div-item"&gt;
        &lt;ion-label&gt;&lt;/ion-label&gt;
        &lt;ion-note&gt;&lt;/ion-note&gt;
    &lt;/div&gt;
    &lt;ion-button slot="end" fill="clean" size="large" (click)="play(index!)"&gt;
        &lt;ion-icon name="play-circle-outline"&gt;&lt;/ion-icon&gt;
    &lt;/ion-button&gt;
    &lt;/ion-item&gt;
</code></pre>

<ul>
  <li>Then open the <code>videoitem.component.scss</code> file and define the css for the <code>div-item</code> class.</li>
</ul>

<pre><code class="language-css">    .div-item  {
        display: flex;
        flex-direction: column;
    }
</code></pre>

<ul>
  <li>Now create the code related to this component by opening the <code>videoitem.component.ts</code> file.</li>
</ul>

<pre><code class="language-ts">    import { CommonModule } from '@angular/common';
    import { ChangeDetectionStrategy, Component, OnInit, Input } from '@angular/core';
    import { RouterLink } from '@angular/router';
    import { IonItem, IonLabel, IonIcon, IonAvatar, IonButton, IonNote } from '@ionic/angular/standalone';
    import { addIcons } from 'ionicons';
    import { playCircleOutline } from 'ionicons/icons';
    import { Video } from '../../services/data.service';
    import { Router } from '@angular/router';

    @Component({
    selector: 'app-videoitem',
    templateUrl: './videoitem.component.html',
    styleUrls: ['./videoitem.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    standalone: true,
    imports: [CommonModule, RouterLink, IonItem, IonLabel, IonIcon,
                IonAvatar, IonButton, IonNote],
    })
    export class VideoitemComponent implements OnInit {
        @Input() video?: Video;
        @Input() index?: number;
        platform: string = 'web';

        constructor(private route: Router) {
                addIcons({ playCircleOutline });
        }

        ngOnInit() {}


        async play(index: number) {
            this.route.navigate([`/viewvideo/${index}`]);
        }
    }

</code></pre>

<h3 id="serve-the-application">Serve the Application</h3>

<p>To get the platform, we use the Capacitor Device plugin, so we first need to install it.</p>

<ul>
  <li>Install @capacitor/device</li>
</ul>

<pre><code class="language-bash">    npm i --save @capacitor/device
</code></pre>

<ul>
  <li>Remove the route to the <code>message/:id</code> if it exists in the <code>app.route.ts</code> file.</li>
</ul>

<pre><code class="language-ts">-   {
-        path: 'message/:id',
-        loadComponent: () =&gt;
-        import('./view-message/view-message.page').then((m) =&gt; m.ViewMessagePage),
-    },
</code></pre>

<ul>
  <li>Run the app</li>
</ul>

<pre><code class="language-bash">    npm run start
</code></pre>

<ul>
  <li>The application will look like has below in the Web browser.</li>
</ul>

<div align="center"><br /><img src="/images/Ionic7-Angular-VideoList.png" width="50%" /></div>
<p><br /></p>

<h3 id="install-the-capacitor-video-player-plugin">Install the Capacitor Video Player Plugin</h3>

<ul>
  <li>Install capacitor-video-player plugin using below command :</li>
</ul>

<pre><code class="language-bash">    npm install --save capacitor-video-player@latest
</code></pre>

<h3 id="create-the-viewvideo-page">Create the Viewvideo Page</h3>

<ul>
  <li>Create the <code>viewvideo</code> page which implements the <code>capacitor-video-player</code> to show a selected video full screen. For this we are using the <code>Ionic CLI</code>.</li>
</ul>

<pre><code class="language-bash"> ionic generate page pages/viewvideo
</code></pre>

<ul>
  <li>If the page <code>viewvideo</code> was successfully created, open the <code>viewvideo.page.html</code> and copy the code into it.</li>
</ul>

<pre><code class="language-html">    &lt;ion-header [translucent]="true"&gt;
        &lt;ion-toolbar&gt;
            &lt;ion-buttons slot="start"&gt;
            &lt;ion-back-button defaultHref="/home"&gt;&lt;/ion-back-button&gt;
            &lt;/ion-buttons&gt;
            &lt;ion-title&gt;viewvideo&lt;/ion-title&gt;
        &lt;/ion-toolbar&gt;
    &lt;/ion-header&gt;

    &lt;ion-content [fullscreen]="true"&gt;
        &lt;ion-header collapse="condense"&gt;
            &lt;ion-toolbar&gt;
            &lt;ion-title size="large"&gt;viewvideo&lt;/ion-title&gt;
            &lt;/ion-toolbar&gt;
        &lt;/ion-header&gt;
        &lt;!-- Mandatory id="fullscreen"  --&gt;
        &lt;div id="fullscreen" slot="fixed"&gt;
        &lt;/div&gt;
    &lt;/ion-content&gt;
</code></pre>

<pre><code>I draw your attention to the &lt;div id="fullscreen"&gt; tag, which is mandatory for the capacitor video player to work well.
</code></pre>

<ul>
  <li>Open the <code>viewvideo.page.scss</code> copy the following css.</li>
</ul>

<pre><code class="language-css">    #fullscreen {
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        background-color: #000000;
    }
</code></pre>

<ul>
  <li>Then, open the <code>viewvideo.page.ts</code> and replace the code by the following.</li>
</ul>

<pre><code class="language-ts">    import { Component, OnInit, AfterViewInit, inject } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { FormsModule } from '@angular/forms';
    import { IonicModule } from '@ionic/angular';
    import { ActivatedRoute, Router } from '@angular/router';
    import { Device } from '@capacitor/device';
    import { CapacitorVideoPlayer } from 'capacitor-video-player';
    import { DataService, Video} from '../../services/data.service';

    @Component({
        selector: 'app-viewvideo',
        templateUrl: './viewvideo.page.html',
        styleUrls: ['./viewvideo.page.scss'],
        standalone: true,
        imports: [IonicModule, CommonModule, FormsModule]
    })
    export class ViewvideoPage implements OnInit, AfterViewInit {
        private data = inject(DataService);
        private videoIndex: number = 0;
        private videoPlayer: any;
        private platform: string = 'web';
        private video: Video | null = {} as Video;

        private handlerPlay: any;
        private handlerPause: any;
        private handlerEnded: any;
        private handlerReady: any;
        private handlerExit: any;

        constructor(private route: ActivatedRoute,
            private navRoute: Router) { }

        //***********************************
        // Component Lifecycle hook methods *
        //***********************************

        ngOnInit() {
            // Subscribe to the params observable to read the id parameter
            this.route.params.subscribe(params =&gt; {
            // Extract the 'id' parameter from the route
            this.videoIndex = +params['id'];
            console.log(this.videoIndex);
            });
        }

        async ngAfterViewInit() {
            // Get the selected video
            this.video = this.data.getVideo(this.videoIndex);

            // Define the platform and the video player
            const info = await Device.getInfo();
            this.platform = info.platform;
            this.videoPlayer = CapacitorVideoPlayer;

            // add plugin listeners
            await this.addListenersToPlayerPlugin();
            const props: any = {};

            // Initialize the video player
            if (this.video!.url != null) {
            props.mode = "fullscreen";
            props.url = this.video!.url;
            props.playerId = 'fullscreen';
            props.componentTag = 'app-viewvideo';
            if(this.video!.subtitle != null) props.subtitle = this.video!.subtitle;
            if(this.video!.stlang != null) props.stlang = this.video!.stlang;
            const res: any = await this.videoPlayer.initPlayer(props);
            }

        }

        async ngOnDestroy(): Promise&lt;void&gt; {
            // Remove the plugin listeners
            await this.handlerPlay.remove();
            await this.handlerPause.remove();
            await this.handlerEnded.remove();
            await this.handlerReady.remove();
            await this.handlerExit.remove();
            await this.videoPlayer.stopAllPlayers();
            return;
        }

        // *******************
        // Private Functions *
        // *******************

        // Define the plugin listeners
        private async addListenersToPlayerPlugin(): Promise&lt;void&gt; {
            this.handlerPlay = await this.videoPlayer.addListener('jeepCapVideoPlayerPlay',
            (data: any) =&gt; {
                const fromPlayerId = data.fromPlayerId;
                const currentTime = data.currentTime;
                console.log(`&lt;&lt;&lt;&lt; onPlay in ViewerVideo ${fromPlayerId} ct: ${currentTime}`);
            }, false);
            this.handlerPause = await this.videoPlayer.addListener('jeepCapVideoPlayerPause',
            (data: any) =&gt; {
                const fromPlayerId = data.fromPlayerId;
                const currentTime = data.currentTime;
                console.log(`&lt;&lt;&lt;&lt; onPause in ViewerVideo ${fromPlayerId} ct: ${currentTime}`);
            }, false);
            this.handlerEnded = await this.videoPlayer.addListener('jeepCapVideoPlayerEnded',
            (data: any) =&gt; {
                const fromPlayerId = data.fromPlayerId;
                const currentTime = data.currentTime;
                console.log(`&lt;&lt;&lt;&lt; onEnded in ViewerVideo ${fromPlayerId} ct: ${currentTime}`);
                this.playerLeave();
            }, false);
            this.handlerExit = await this.videoPlayer.addListener('jeepCapVideoPlayerExit',
            (data: any) =&gt; {
                const dismiss = data.dismiss ;
                console.log(`&lt;&lt;&lt;&lt; onExit in ViewerVideo ${dismiss}`);
                this.playerLeave();
            }, false);
            this.handlerReady = await this.videoPlayer.addListener('jeepCapVideoPlayerReady',
            (data: any) =&gt; {
                const fromPlayerId = data.fromPlayerId;
                const currentTime = data.currentTime;
                console.log(`&lt;&lt;&lt;&lt; onReady in ViewerVideo ${fromPlayerId} ct: ${currentTime}`);
            }, false);
            return;
        }

        // Action when the player ended or exit
        private playerLeave() {
            this.navRoute.navigate(['/home']);
            return;
        }
    }
</code></pre>

<ul>
  <li>Finally, open the <code>app.routes.ts</code> file and update the path.</li>
</ul>

<pre><code class="language-ts">    path: 'viewvideo'
</code></pre>

<p>with</p>

<pre><code class="language-ts">    path: 'viewvideo/:id'
</code></pre>

<p>In this <code>viewvideo</code> page, we saw how to</p>

<ul>
  <li>
    <p>Initialize the <code>capcitor-video-player</code> with the <code>initPlayer</code> API method which has some options as arguments. We have used only few of them.</p>

    <ul>
      <li>The complete list of options is given below.</li>
    </ul>

    <pre><code class="language-json">    {
        /**
        * Player mode
        *  - "fullscreen"
        *  - "embedded" (Web only)
        */
        mode?: string;
        /**
        * The url of the video to play
        */
        url?: string;
        /**
        * The url of subtitle associated with the video
        */
        subtitle?: string;
        /**
        * The language of subtitle
        * see https://github.com/libyal/libfwnt/wiki/Language-Code-identifiers
        */
        language?: string;
        /**
        * SubTitle Options
        */
        subtitleOptions?: SubTitleOptions;
        /**
        * Id of DIV Element parent of the player
        */
        playerId?: string;
        /**
        * Initial playing rate
        */
        rate?: number;
        /**
        * Exit on VideoEnd (iOS, Android)
        * default: true
        */
        exitOnEnd?: boolean;
        /**
        * Loop on VideoEnd when exitOnEnd false (iOS, Android)
        * default: false
        */
        loopOnEnd?: boolean;
        /**
        * Picture in Picture Enable (iOS, Android)
        * default: true
        */
        pipEnabled?: boolean;
        /**
        * Background Mode Enable (iOS, Android)
        * default: true
        */
        bkmodeEnabled?: boolean;
        /**
        * Show Controls Enable (iOS, Android)
        * default: true
        */
        showControls?: boolean;
        /**
        * Display Mode ["portrait", "landscape"] (iOS, Android)
        * default: "portrait"
        */
        displayMode?: string;
        /**
        * Component Tag or DOM Element Tag (React app)
        */
        componentTag?: string;
        /**
        * Player Width (mode "embedded" only)
        */
        width?: number;
        /**
        * Player height (mode "embedded" only)
        */
        height?: number;
        /**
        * Headers for the request (iOS, Android)
        * by Manuel García Marín (https://github.com/PhantomPainX)
        */
        headers?: {
            [key: string]: string;
        };
        /**
        * Title shown in the player (Android)
        * by Manuel García Marín (https://github.com/PhantomPainX)
        */
        title?: string;
        /**
        * Subtitle shown below the title in the player (Android)
        * by Manuel García Marín (https://github.com/PhantomPainX)
        */
        smallTitle?: string;
        /**
        * ExoPlayer Progress Bar and Spinner color (Android)
        * by Manuel García Marín (https://github.com/PhantomPainX)
        * Must be a valid hex color code
        * default: #FFFFFF
        */
        accentColor?: string;
        /**
        * Chromecast enable/disable (Android)
        * by Manuel García Marín (https://github.com/PhantomPainX)
        * default: true
        */
        chromecast?: boolean;
        /**
        * Artwork url to be shown in Chromecast player
        * by Manuel García Marín (https://github.com/PhantomPainX)
        * default: ""
        */
        artwork?: string;
    } 
</code></pre>
  </li>
  <li>
    <p>Set the Capacitor Video Player plugin events.</p>

    <ul>
      <li>jeepCapVideoPlayerPlay : Emitted when the video starts to play</li>
      <li>jeepCapVideoPlayerPause: Emitted when the video is paused</li>
      <li>jeepCapVideoPlayerReady: Emitted when the video is ready to play</li>
      <li>jeepCapVideoPlayerEnded: Emitted when the video has ended</li>
      <li>jeepCapVideoPlayerExit: Emitted when the exit player button is pressed</li>
    </ul>
  </li>
  <li>
    <p>Use the <code>jeepCapVideoPlayerEnded</code> and <code>jeepCapVideoPlayerExit</code> events to leave the <code>viewvideo</code> page and root back to the <code>home</code> page.</p>
  </li>
</ul>

<h3 id="capacitor-video-player-api-methods">Capacitor Video Player API methods</h3>

<ul>
  <li>
    <p>Below find the list of the API methods.</p>

    <ul>
      <li>initPlayer(options)       Initialize a video player</li>
      <li>isPlaying(options)        Give the video player’s status</li>
      <li>play(options)             Start playing a video</li>
      <li>pause(options)            Pause the video</li>
      <li>getDuration()             Get the video’s duration</li>
      <li>getCurrentTime(options)   Get the video’s current time</li>
      <li>setCurrentTime(options)   Set the current time to seek</li>
      <li>getVolume(options)        Get the video’s volume</li>
      <li>setVolume(options)        Set the video’s volume</li>
      <li>getMuted(options)         Get the video’s muted</li>
      <li>setMuted(options)         Set the video’s muted</li>
      <li>setRate()                 Set the video’s rate</li>
      <li>getRate(options)          Get the video’s rate</li>
      <li>stopAllPlayers()          Stop all players playing</li>
      <li>showController()          Show controller</li>
      <li>isControllerIsFullyVisible() Give the controller’s status</li>
      <li>exitPlayer()              Exit the player</li>
    </ul>
  </li>
</ul>

<h3 id="run-the-web-application">Run the Web Application</h3>

<ul>
  <li>Run the app</li>
</ul>

<pre><code class="language-bash">    npm run start
</code></pre>

<ul>
  <li>
    <p>The application will look like has below in the Web browser.</p>

    <video width="90%" controls="">
   <source src="/videos/IonicAngularVideoPlayerAppWeb.mp4" type="video/mp4" />
 </video>
    <p><br /></p>
  </li>
</ul>

<h3 id="prepare-for-native-applications">Prepare for Native Applications</h3>

<ul>
  <li>Install @capacitor/ios and @capacitor/android.</li>
</ul>

<pre><code class="language-bash">    npm install @capacitor/ios @capacitor/android
</code></pre>

<ul>
  <li>
    <p>Edit <code>appId</code> in the <code>capacitor.config.ts</code> with YOUR_APP_ID.</p>
  </li>
  <li>
    <p>Edit <code>appName</code> in the <code>capacitor.config.ts</code> with YOUR_APP_NAME.</p>
  </li>
  <li>
    <p>Create a production build.</p>
  </li>
</ul>

<pre><code class="language-bash">    npm run build --prod
</code></pre>

<ul>
  <li>Add iOS platform.</li>
</ul>

<pre><code class="language-bash">    npx cap add ios
</code></pre>

<ul>
  <li>Add Android platform.</li>
</ul>

<pre><code class="language-bash">    npx cap add android
</code></pre>

<ul>
  <li>Copy the Ionic build to iOS and Android platforms.</li>
</ul>

<pre><code class="language-bash">    npx cap copy
</code></pre>

<h3 id="run-the-ios-application">Run the iOS Application</h3>

<pre><code class="language-bash">    npx cap open ios
</code></pre>

<ul>
  <li>
    <p>For <code>Picture-in-Picture</code> enabling in Xcode go to <code>App-Signing Capabilities-Background Modes</code> and click on `Audio, Airplay, and Picture in Picture.</p>
  </li>
  <li>
    <p>The application will look like has below in the iOS Device.</p>

    <video width="50%" controls="">
   <source src="/videos/Ionic7AngularVideoPlayerAppIOS.mov" type="video/mp4" />
 </video>
    <p><br /></p>
  </li>
</ul>

<h3 id="run-the-android-application">Run the Android Application</h3>

<pre><code class="language-bash">    npx cap open android
</code></pre>

<ul>
  <li>In AndroidStudio got to Preferences-&gt;Build,Execution,Deployment-&gt;Build Tools-&gt;Gradle
    <ul>
      <li>modify Gradle JDK to <code>17 Oracle OpenJDK version 17.0.7</code>.</li>
      <li>click on <code>Apply</code>and <code>OK</code>.</li>
    </ul>
  </li>
  <li>Add these lines in the <code>AndroidManifest.xml</code> file</li>
</ul>

<pre><code class="language-xml">    &lt;meta-data
        android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
        android:value="com.google.android.exoplayer2.ext.cast.DefaultCastOptionsProvider"&gt;
    &lt;/meta-data&gt;
</code></pre>

<p>then, add these lines for Picture-in-Picture enabling somewhere in the  <code>&lt;activity ...&gt;</code></p>

<pre><code class="language-xml">    android:resizeableActivity="true"
    android:supportsPictureInPicture="true"
</code></pre>

<p>and</p>

<pre><code class="language-xml">     &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32"/&gt;
</code></pre>

<ul>
  <li>Add this dependency in the <code>build.gradle(Project: android)</code> file under dependencies</li>
</ul>

<pre><code class="language-xml">    classpath 'com.google.gms:google-services:4.4.0'
</code></pre>

<ul>
  <li>Add this implementation in the <code>build.gradle(Module: app)</code>file under dependencies</li>
</ul>

<pre><code class="language-xml">     implementation 'com.google.android.gms:play-services-cast-framework:21.3.0'
</code></pre>

<ul>
  <li>In <code>variables.gradle</code> file modify</li>
</ul>

<pre><code class="language-xml"> coreSplashScreenVersion = '1.0.1'
</code></pre>
<ul>
  <li>
    <p>Go to File-&gt;Sync Project with Gradle files.</p>
  </li>
  <li>
    <p>Build and run the application</p>
  </li>
  <li>
    <p>The application will look like has below in the AndroidDevice.</p>

    <video width="50%" controls="">
   <source src="/videos/Ionic7AngularVideoPlayerAppAndroid.mov" type="video/mp4" />
 </video>
    <p><br /></p>
  </li>
</ul>

<h3 id="how-to-play-local-videos-in-android-and-ios">How to Play Local Videos in Android and iOS</h3>

<p>In this added part of the tutorial, you will learned, how to download a video to a local devices’s directory and define the url of this video to be played by the video player.</p>

<p>This will required to update <code>data.service.ts</code> to fetch the video, write it to the device and define the local uri of the video.</p>

<p>First, install the <code>@capacitor-community/filesystem</code>.</p>

<pre><code class="language-bash">npm i @capacitor-community/filesystem
</code></pre>

<p>In your favorite Editor, open the file <code>data.services.ts</code> and update it accordingly</p>

<pre><code class="language-ts">  import { Injectable } from '@angular/core';
  import { Filesystem, Directory, StatOptions } from '@capacitor/filesystem';
  import { Capacitor } from '@capacitor/core';

  export interface Video {
    id: number;
    device: string;
    type: string;
    title: string;
    url: string;
    thumb?: string;
    note: string;
    subtitle?: string;
    stlang?: string;
  }


  @Injectable({
    providedIn: 'root'
  })
  export class DataService {
    private videos: Video[] = [
      {
        id: 1,
        type: "mp4",
        device: "all",
        url: "https://brenopolanski.github.io/html5-video-webvtt-example/MIB2.mp4",
        note: "Breno Polanski",
        title: "Test MP4 with Subtitle",
        subtitle: "https://brenopolanski.github.io/html5-video-webvtt-example/MIB2-subtitles-pt-BR.vtt",
        stlang: "es"
      },
      {
        id: 2,
        type: "mp4",
        device: "all",
        url: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
        note: "By Blender Foundation",
        thumb: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg",
        title: "Big Buck Bunny"
      },
      {
        id: 3,
        type: "mp4",
        device: "all",
        url: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4",
        note: "By Blender Foundation",
        thumb: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/ElephantsDream.jpg",
        title: "Elephant Dream"
      },
      {
        id: 4,
        type: "mp4",
        device: "all",
        url: "https://media.bernat.ch/videos/2019-self-hosted-videos-subtitles/progressive.mp4",
        note: "Blender Animation Studio",
        thumb: "https://d2pzklc15kok91.cloudfront.net/images/posters/2019-self-hosted-videos-subtitles.3b55d44c736235.jpg",
        title: "327",
        subtitle: "https://media.bernat.ch/videos/2019-self-hosted-videos-subtitles.en.vtt",
        stlang: "en"
      },
      {
        id: 5,
        type: "aws",
        device: "all",
        url: "https://universo-dev-a-m.s3.amazonaws.com/779970/fe774806dbe7ad042c24ce522b7b46594f16c66e",
        note: "Custom",
        title: "AWS video test",
      },
      {
        id: 6,
        type: "hls",
        device: "all",
        url: "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8",
        note: "By Blender Foundation",
        title: "Big Buck Bunny",
      },
      {
        id: 7,
        type: "mpd",
        device: "android",
        url: "https://bitmovin-a.akamaihd.net/content/MI201109210084_1/mpds/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.mpd",
        note: "",
        title: "MPD video test",
      },
      {
        id: 8,
        type: "webm",
        device: "android",
        url: "https://upload.wikimedia.org/wikipedia/commons/f/f1/Sintel_movie_4K.webm",
        note: "Blender Foundation",
        thumb: "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Sintel_movie_4K.webm/800px--Sintel_movie_4K.webm.jpg?20150505130125",
        title: "Webm video test",
      },
      {
        id: 9,
        type: "mp4",
        device: "android",
        url: "public/assets/video/Bike720.mp4",
        note: "",
        title: "Video from Assets directory",
      },
      {
        id: 10,
        type: "mp4",
        device: "android",
        url: "file:///storage/emulated/0/Documents/Bike720.mp4",
        note: "",
        title: "Video on Documents directory",
      },
      {
        id: 11,
        type: "mp4",
        device: "android",
        url: "file:///sdcard/Download/Bike720.mp4",
        note: "",
        title: "Video on sdcard Download directory",
      },
      {
        id: 12,
        type: "mp4",
        device: "android",
        url: "file:///sdcard/DCIM/Camera/Bike720.mp4",
        note: "",
        title: "Video on sdcard DCIM directory",
      },
      {
        id: 13,
        type: "mp4",
        device: "android",
        url: "file:///sdcard/Documents/KSSV/documents/1/videos/2-12-2023-101222.mp4",
        note: "",
        title: "Video on sdcard issue#142 directory",
      },
      {
        id: 14,
        type: "mp4",
        device: "ios",
        url: "public/assets/video/Bike720.mp4",
        note: "",
        title: "Video from Assets directory",
      },
      {
        id: 15,
        type: "mp4",
        device: "ios",
        url: "file:///var/mobile/Containers/Data/Application/22A433FD-D82D-4989-8BE6-9FC49DEA20BB/Documents/Bike720.mp4",
        note: "",
        title: "Video on App's Documents directory",
      },
      {
        id: 16,
        type: "mp4",
        device: "ios",
        url: "file:///var/mobile/Documents/Bike720.mp4",
        note: "",
        title: "Video on Documents directory",
      },
      {
        id: 17,
        type: "mp4",
        device: "ios",
        url: "file:///var/mobile/Downloads/Bike720.mp4",
        note: "",
        title: "Video on Download directory",
      },
      {
        id: 18,
        type: "mp4",
        device: "ios",
        url: "file:///var/mobile/Media/DCIM/100APPLE/Bike720.mp4",
        note: "",
        title: "Video on Media/DCIM directory",
      },
      {
        id: 19,
        type: "mp4",
        device: "all",
        url: "https://raw.githubusercontent.com/jepiqueau/jepiqueau.github.io/master/videos/Bike720.mp4",
        note: "Test Bike720",
        title: "Video from ",
      },


  ];

    constructor() {
      this.createDeviceVideo();
    }


    public getVideos(platform: string): Video[] {
      if (platform === 'web') {
        // Filter videos for Web platform (device: 'all')
        return this.videos.filter((video) =&gt; video.device === 'all');
      } else if (platform === 'android') {
        // Filter videos for Android platform (device: 'all' or 'android')
        return this.videos.filter((video) =&gt; video.device === 'all' || video.device === 'android');
      } else if (platform === 'ios') {
        // Filter videos for iOS platform (device: 'all' or 'ios')
        return this.videos.filter((video) =&gt; video.device === 'all' || video.device === 'ios');
      } else {
        return [];
      }
    }
    public getVideoById(id: number): Video | undefined {
      return this.videos.find(video =&gt; video.id === id);
    }
    private async createDeviceVideo(): Promise&lt;void&gt; {
      const platform = Capacitor.getPlatform();
      if (['ios', 'android'].includes(platform)) {
        // file Bike720.mp4
        const urlBike = "https://raw.githubusercontent.com/jepiqueau/jepiqueau.github.io/master/videos/Bike720.mp4";

        const uri = await this.fetchingVideoToDevice(urlBike, Directory.Documents);
        console.log(`###### uri : ${uri} ######`)
        if(uri !== undefined) {
          await this.copyVideoToOthersDirectories(uri,platform);
        }
        // test with a given path
        const vUri = await this.fetchingVideoToDevice(urlBike, Directory.Documents,"KSSV/documents/1/videos/2-12-2023-101222.mp4" );
        console.log(`###### vUri : ${vUri} ######`)

      }
    }

    public async fetchingVideoToDevice(url:string, directory: Directory, path: string = ""): Promise&lt;string | undefined&gt; {
      const urlName = path.length === 0 ? this.getFileName(url)! : path;
      const isVideoExists = await this.isFileExists(urlName, directory);
      if(!isVideoExists) {
        let response = await fetch(url);
        let dbBlob = await response.blob();
        let vBase64 = await this.getBlobAsBase64(dbBlob);
        await Filesystem.writeFile({ data: vBase64, path: urlName, recursive: true, directory: directory });
        return (await Filesystem.getUri({
          path: urlName,
          directory: Directory.Documents
        })).uri;

      } else {
        return (await Filesystem.getUri({
          path: urlName,
          directory: Directory.Documents
        })).uri;
      }

    }
    private getBlobAsBase64(blob: Blob): Promise&lt;string&gt; {
      return new Promise((resolve, _) =&gt; {
        let reader = new FileReader();
        reader.onload = (event: any) =&gt; {
          resolve(event.target.result);
        };
        reader.readAsDataURL(blob);
      });
    }

    private async copyVideoToOthersDirectories(uri: string,platform: string): Promise&lt;void&gt; {
      // Copy a video to others local device's directory

      const uriName = this.getFileName(uri);
      let toPathDocum: string = "";
      let toPathDownl: string = "";
      let toPathDCIM: string = "";
      if (platform === 'ios') {
        const containersIndex = uri.indexOf('Containers');
        const folderPath = containersIndex !== -1 ? uri.substring(0, containersIndex) : uri;
        toPathDocum = `${folderPath}Documents/${uriName!}`;
        toPathDownl = `${folderPath}Downloads/${uriName!}`;
        toPathDCIM = `${folderPath}Media/DCIM/100APPLE/${uriName!}`;
      } else if (platform === 'android') {
        const parentPathIndex = uri.indexOf('Documents');
        const parentPath = parentPathIndex !== -1 ? uri.substring(0, parentPathIndex) : uri;
        toPathDownl = `${parentPath}Download/${uriName!}`;
        toPathDCIM = `${parentPath}DCIM/Camera/${uriName!}`;
      }

      if(toPathDocum.length &gt; 0 &amp;&amp; !(await this.isFileExists(toPathDocum))) {
        const rc1 = await Filesystem.copy ({
          from: uri,
          to: toPathDocum
        });
      }
      if(toPathDownl.length &gt; 0 &amp;&amp; !(await this.isFileExists(toPathDownl))) {
        const rc2 = await Filesystem.copy ({
          from: uri,
          to: toPathDownl
        });
      }
      if(toPathDCIM.length &gt; 0 &amp;&amp; !(await this.isFileExists(toPathDCIM))) {
        const rc3 = await Filesystem.copy ({
          from: uri,
          to: toPathDCIM
        });
      }
    }

    private async isFileExists(path: string, directory?: Directory): Promise&lt;boolean&gt; {

      try {
        const options: StatOptions = {} as StatOptions;
        options.path = path;
        const dir = directory ? directory : "";
        if (dir.length &gt; 0) options.directory = directory;
        const info = await Filesystem.stat(options);
        console.log(`&amp;&amp;&amp;&amp;&amp; info: ${JSON.stringify(info)} &amp;&amp;&amp;&amp;&amp;`)
        return true;
      } catch (error) {
        return false;
      }
    }
    private getFileName(url: string) : string | undefined{
      const urlObject = new URL(url);
      return urlObject.pathname.split('/').pop();
    }
  }
</code></pre>

<p>In this Typescript version,</p>

<ul>
  <li>
    <p>an <code>id</code> parameter was added to the video interface and then the video list was updated accordingly. This will imply a modification the <code>videoitem</code> component.</p>
  </li>
  <li>
    <p>a call to a <code>createDeviceVideo</code> method to create the local video in the constructor</p>
  </li>
  <li>
    <p>in this <code>createDeviceVideo</code> method, the video <code>Bike720.mp4</code> is fetch from the <code>https://raw.githubusercontent.com/jepiqueau/jepiqueau.github.io/master/videos/</code> and written to a local device’s directory and then copy to several local device’s directories for demonstrating the local uri which may be used.</p>
  </li>
  <li>
    <p>example of local uri for :</p>

    <ul>
      <li>Android : “file:///storage/emulated/0/Documents/Bike720.mp4”,</li>
      <li>iOS: “file:///var/mobile/Documents/Bike720.mp4”.</li>
    </ul>
  </li>
</ul>

<p>Now modify the videoitem component</p>

<ul>
  <li>
    <p>open the <code>videoitem.component.html</code> file and replace the code with:</p>

    <pre><code class="language-ts">&lt;ion-item&gt;
  &lt;ion-avatar slot="start"&gt;
    &lt;img [src]="video!.thumb" /&gt;
  &lt;/ion-avatar&gt;
  &lt;div class="div-item"&gt;
    &lt;ion-label&gt;&lt;/ion-label&gt;
    &lt;ion-note&gt;&lt;/ion-note&gt;
  &lt;/div&gt;
  &lt;ion-button slot="end" fill="clean" size="large" (click)="play()"&gt;
    &lt;ion-icon name="play-circle-outline"&gt;&lt;/ion-icon&gt;
  &lt;/ion-button&gt;
&lt;/ion-item&gt;
</code></pre>
  </li>
  <li>
    <p>open the <code>videoitem.component.ts</code> and update it as:</p>

    <pre><code class="language-ts">  import { CommonModule } from '@angular/common';
  import { ChangeDetectionStrategy, Component, OnInit, Input } from '@angular/core';
  import { RouterLink } from '@angular/router';
  import { IonItem, IonLabel, IonIcon, IonAvatar, IonButton, IonNote } from '@ionic/angular/standalone';
  import { addIcons } from 'ionicons';
  import { playCircleOutline } from 'ionicons/icons';
  import { Video } from '../../services/data.service';
  import { Router } from '@angular/router';

  @Component({
    selector: 'app-videoitem',
    templateUrl: './videoitem.component.html',
    styleUrls: ['./videoitem.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    standalone: true,
    imports: [CommonModule, RouterLink, IonItem, IonLabel, IonIcon,
              IonAvatar, IonButton, IonNote],
  })
  export class VideoitemComponent implements OnInit {
    @Input() video?: Video;

    constructor(private route: Router) {
          addIcons({ playCircleOutline });
    }

    ngOnInit() {
      if (!this.video!.hasOwnProperty('thumb')) {
        this.video!.thumb = 'https://avatars3.githubusercontent.com/u/16580653?v=4';
      }
      console.log(`***** in ngOnInit id: ${this.video!.id} video title: ${this.video!.title}`)
    }


    async play() {

      console.log(`***** id: ${this.video!.id}, video title: ${this.video!.title}`)
      this.route.navigate([`/viewvideo/${this.video!.id}`]);
    }
  }
</code></pre>
  </li>
</ul>

<p>Then open the <code>viewvideo.page.ts</code> and replace</p>

<pre><code class="language-ts">      this.video = this.data.getVideo(this.videoIndex);
</code></pre>

<p>by</p>

<pre><code class="language-ts">      this.video = this.data.getVideoById(this.videoIndex);
</code></pre>

<p>Rebuild the code.</p>

<h3 id="conclusion">Conclusion</h3>

<p>We have completed the Ionic 7 VideoPlayer App Example Tutorial using Angular framework and the capacitor-video-player plugin.</p>

<p>We learned how to implement the <code>capacitor-video-player</code> plugin in the Angular Framework using Ionic UI component toolkit, and Ionic Capacitor which add native functionality.</p>

<p>We learned how to play local device’s videos.</p>

<p>Enjoy your development from there.</p>]]></content><author><name>Quéau Jean Pierre</name></author><category term="Other" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Vant Nuxt Capacitor Video Player Example Tutorial using Nuxt, Vant and the capacitor-video-player plugin</title><link href="https://jepiqueau.github.io/2023/11/06/Vant-Nuxt-Capacitor-VideoPlayer-App.html" rel="alternate" type="text/html" title="Vant Nuxt Capacitor Video Player Example Tutorial using Nuxt, Vant and the capacitor-video-player plugin" /><published>2023-11-06T00:00:00+00:00</published><updated>2023-11-06T00:00:00+00:00</updated><id>https://jepiqueau.github.io/2023/11/06/Vant-Nuxt-Capacitor-VideoPlayer-App</id><content type="html" xml:base="https://jepiqueau.github.io/2023/11/06/Vant-Nuxt-Capacitor-VideoPlayer-App.html"><![CDATA[<hr />

<p><em>last updated on November 6, 2023 by Quéau Jean Pierre</em></p>

<p>In that tutorial we will learned how to create a Vant Nuxt application and implement the capacitor-video-player plugin to play video.</p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/vant-nuxt-videoplayer-app">vant-nuxt-videoplayer</a></p>

<h2 id="table-of-contents">Table of Contents</h2>

<hr />
<ul>
  <li><a href="#install-new-nuxt-application">Install New Nuxt Application</a></li>
  <li><a href="#change-the-name-of-the-application">Change the name of the application</a></li>
  <li><a href="#install-vant">Install Vant</a></li>
  <li><a href="#install-capacitor">Install Capacitor</a></li>
  <li><a href="#modify-appvue">Modify app.vue</a></li>
  <li><a href="#create-page-index-and-about">Create Page Index and About</a></li>
  <li><a href="#create-custom-pageheader-component">Create Custom PageHeader Component</a></li>
  <li><a href="#install-capacitor-video-player-plugin">Install capacitor-video-player plugin</a></li>
  <li><a href="#create-video-utilities">Create Video Utilities</a></li>
  <li><a href="#create-composables">Create Composables</a></li>
  <li><a href="#create-fullscreenvideoplayer-component">Create FullscreenVideoPlayer Component</a></li>
  <li><a href="#create-viewer-video-page">Create Viewer Video Page</a></li>
  <li><a href="#reference-the-videoviewer-page-in-index-page">Reference the VideoViewer Page in Index Page</a></li>
  <li><a href="#run-the-application-in-the-web-browser">Run the Application in the Web Browser</a>
 -<a href="#run-the-application-in-ios-device">Run the Application in iOS Device</a>
 -<a href="#run-the-application-in-android-device">Run the Application in Android Device</a>
 -<a href="#conclusion">Conclusion</a></li>
</ul>

<h3 id="install-new-nuxt-application">Install New Nuxt Application</h3>

<ul>
  <li>Run the below command.</li>
</ul>

<pre><code class="language-bash"> npx nuxi@latest init vant-nuxt-videoplayer-app
</code></pre>
<p>and select which package manager you would like to use. Below we assume that <code>npm</code> has been selected. If you have selected <code>pnpm</code> or <code>yarn</code> or <code>bun</code>, please adapt the following given commands.</p>

<h3 id="change-the-name-of-the-application">Change the name of the application</h3>

<ul>
  <li>Open the <code>package.json</code> file and change the name.</li>
</ul>

<pre><code class="language-json"> {
 "name": "vant-nuxt-videoplayer-app"
 ...
 }
</code></pre>

<ul>
  <li>Open the <code>package-lock.json</code> file and change the name.</li>
</ul>

<pre><code class="language-json"> {
 "name": "vant-nuxt-videoplayer-app",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "vant-nuxt-videoplayer-app",
      ...
    }
    ...
  }
 }
</code></pre>

<h3 id="install-vant">Install Vant</h3>

<ul>
  <li>Run the following command.</li>
</ul>

<pre><code class="language-bash"> npm i --save-dev vant @vant/nuxt
</code></pre>

<ul>
  <li>open <code>nuxt.config.ts</code> file in your favorite file editor and modify it as shown.</li>
</ul>

<pre><code class="language-ts">    // https://nuxt.com/docs/api/configuration/nuxt-config
    export default defineNuxtConfig({
    devtools: { enabled: true },
    modules: ['@vant/nuxt'],
    })
</code></pre>

<h3 id="install-capacitor">Install Capacitor</h3>

<ul>
  <li>Run the following commands.</li>
</ul>

<pre><code class="language-bash"> npm i @capacitor/core
 npm i -D @capacitor/cli
</code></pre>

<ul>
  <li>Initialize your Capacitor config</li>
</ul>

<pre><code class="language-bash"> npx cap init
</code></pre>
<p>and answer to the following questions.</p>

<pre><code> ? Name &gt; YOUR_APP_NAME
 ? Package ID &gt; YOUR_PACKAGE_ID
 ? Web asset directory &gt; dist
</code></pre>

<ul>
  <li>Edit the <code>nuxt.config.ts</code>file to look like this.</li>
</ul>

<pre><code class="language-ts">    // https://nuxt.com/docs/api/configuration/nuxt-config
    export default defineNuxtConfig({
    app: {
        head: {
        title: 'Vant Nuxt VideoPlayer App',
        meta: [
            { name: 'viewport', content: 'viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no'},
            { name: 'format-detection', content: 'telephone=no' },
            { name: 'msapplication-tap-highlight', content:'no'},
            { name: 'apple-mobile-web-app-capable', content:'yes' },
            { name: 'apple-mobile-web-app-title', content:'Vant Nuxt VideoPlayer App' },
            { name: 'apple-mobile-web-app-status-bar-style', content:'black'},
        ]
        }
    },
    devtools: { enabled: true },
    modules: ['@vant/nuxt'],

    })
</code></pre>

<h3 id="modify-appvue">Modify app.vue</h3>

<ul>
  <li>open the file <code>app.vue</code> and replace the code by:</li>
</ul>

<pre><code class="language-html">    &lt;template&gt;
    &lt;div&gt;
        &lt;NuxtPage /&gt;
    &lt;/div&gt;
    &lt;/template&gt;
</code></pre>

<h3 id="create-page-index-and-about">Create Page Index and About</h3>

<ul>
  <li>
    <p>Create the <code>pages</code> directory at the root of your project.</p>
  </li>
  <li>
    <p>Create the <code>index.vue</code> file under the pages directory and copy below.</p>
  </li>
</ul>

<pre><code class="language-ts">    &lt;template&gt;
        &lt;div id="home-page"&gt;
            &lt;div id="home-header"&gt;
                &lt;h2&gt;Home Page&lt;/h2&gt;
            &lt;/div&gt;
            &lt;div id="home-container"&gt;
                &lt;nav&gt;
                &lt;van-grid :border="false" :column-num="1"&gt;
                    &lt;van-grid-item&gt;
                        &lt;NuxtLink to="/about" class="n-link-base"&gt;
                            About
                        &lt;/NuxtLink&gt;
                    &lt;/van-grid-item&gt;
                &lt;/van-grid&gt;
                &lt;/nav&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/template&gt;
    &lt;script setup lang="ts"&gt;
    definePageMeta({
        layout:"home",
        alias:["/home", "/"]
    })
    &lt;/script&gt;
    &lt;style scoped&gt;
    #home-page {
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        display: flex;
        position: absolute; 
        z-index: 1;  
    }
    #home-header {
        position:absolute;
        width: 100%;
        top: 40px;
        text-align:center; 
    }
    #home-container {
        position: absolute;
        top: 96px;
        left: 0;
        right: 0;
        bottom: 0;
    }

    &lt;/style&gt;
</code></pre>

<ul>
  <li>Create the <code>about.vue</code> file under the pages directory and copy below.</li>
</ul>

<pre><code class="language-ts">    &lt;template&gt;
        &lt;div id="about-page"&gt;
            &lt;header&gt;
                &lt;PageHeader :title="pageTitle"&gt;&lt;/PageHeader&gt;
            &lt;/header&gt;
            &lt;div id="about-container"&gt;
                &lt;p class="about-content-p"&gt;This is an example of how to use Capacitor Video Player plugin&lt;/p&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/template&gt;
    &lt;script lang="ts"&gt;
    export default defineNuxtComponent({
        name: "about",
        alias: "/about",
        setup() {
            const pageTitle = "About Page";
            return {pageTitle}
        }
    });
    &lt;/script&gt;
    &lt;style scoped&gt;
    #about-page {
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        display: flex;
        position: absolute;
        z-index: 1;   
    }
    #about-container {
        position: absolute;
        top: 96px;
        left: 0;
        right: 0;
        bottom: 0;
    }
    .about-content-p {
        padding: 2%;
    }
    &lt;/style&gt;
</code></pre>

<p>As you can see in the about page, a custom <code>PageHeader</code> component is used.</p>

<h3 id="create-custom-pageheader-component">Create Custom PageHeader Component</h3>

<ul>
  <li>
    <p>Create the <code>components</code> directory at the root of your project.</p>
  </li>
  <li>
    <p>Create the <code>PageHeader.vue</code> file which contains our custom page header that will be used throughout the application.</p>
  </li>
</ul>

<pre><code class="language-ts">    &lt;template&gt;
        &lt;div class="page-header"&gt;
            &lt;NuxtLink to="/" class="page-header-link"&gt;
                Back
            &lt;/NuxtLink&gt;
        &lt;h2&gt;&lt;/h2&gt;
        &lt;/div&gt;
    &lt;/template&gt;
    &lt;script lang="ts"&gt;
    export default defineNuxtComponent({
        name: 'PageHeader',
        props: ['title'],
        setup(props) {
            const title = props.title;
            return {title}
        }
    })
    &lt;/script&gt;
    &lt;style scoped&gt;
    .page-header {
        position:absolute;
        width: 100%;
        top: 40px;
        display:flex;
        flex-direction: row;
        z-index: 1;
    }
    .page-header-link {
        padding-left: 1%;
        padding-right: 1%;
        margin-top: 28px;
    }
    .page-header h2 {
        padding-left: 4%;
        padding-right: 1%;
    }
    &lt;/style&gt;
</code></pre>

<ul>
  <li>Now you can run the app and you must be able to navigate from the Home page to the About page and back to the Home page. Run the following command.</li>
</ul>

<pre><code class="language-bash">    npm run dev
</code></pre>
<h3 id="install-capacitor-video-player-plugin">Install capacitor-video-player plugin</h3>

<ul>
  <li>Execute the following command.</li>
</ul>

<pre><code class="language-bash"> npm i --save capacitor-video-player
</code></pre>

<h3 id="create-video-utilities">Create Video Utilities</h3>

<ul>
  <li>
    <p>Create the <code>interfaces</code> directory at the root of your project.</p>
  </li>
  <li>
    <p>Create the <code>interfaces.ts</code> file under the interfaces directory which will contain the video model.</p>
  </li>
</ul>

<pre><code class="language-ts">    export interface SubtitleOptions {
        backgroundColor?: string,
        fontSize?: number,
        foregroundColor?: string
    }
    export interface VideoModel {
        device: string,
        title?: string,
        description?: string,
        url: string,
        type: string,
        gif?: string,
        published_at: string,
        subtitle_url?: string,
        subtitle_langage?: string,
        subtitle_options?: SubtitleOptions
    }
</code></pre>

<ul>
  <li>
    <p>Create the <code>assets</code> directory at the root of your project and the json subdirectory.</p>
  </li>
  <li>
    <p>Create the <code>videolist.json</code> file under the json directory and fill in as follows.</p>
  </li>
</ul>

<pre><code class="language-json">    {
        "videoList" : [
            {
                "title": "MIB2",
                "description": "Lorem ipsum dolor sit amet. Facilis recusandae ex eaque recusandae non voluptas veniam nam enim modi.",
                "url": "https://brenopolanski.github.io/html5-video-webvtt-example/MIB2.mp4",
                "subtitle_url": "https://brenopolanski.github.io/html5-video-webvtt-example/MIB2-subtitles-pt-BR.vtt",
                "subtitle_langage": "es",
                "subtitle_options":{"backgroundColor":"rgba(0,0,0,0)","fontSize":18,"foregroundColor":"rgba(255,0,0,1)"},
                "type": "mp4",
                "published_at": "July 4 2020 12:30",
                "device": "all"
            },
            {
                "title": "Big Buck Bunny",
                "description": "Eos rerum quia ex repellendus asperiores sit sunt aperiam sed amet adipisci nam dignissimos consectetur qui voluptatem voluptas.",
                "url": "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8",
                "type": "m3u8",
                "published_at": "December 3 2021 17:50",
                "device": "all"
            }
        ]
    }
</code></pre>

<ul>
  <li>
    <p>Create the <code>services</code> directory at the root of your project.</p>
  </li>
  <li>
    <p>Create the <code>video.service.ts</code> file under the services directory and edit it as follows.</p>
  </li>
</ul>

<pre><code class="language-ts">    import videoList from '@/assets/json/videolist.json';
    import type { VideoModel } from '@/interfaces/interfaces';
    import type { Ref } from 'vue';

    export default class VideoService {
        videoList: VideoModel[] = videoList.videoList;
        public async get(contentId: Ref&lt;string | string[]&gt;): Promise&lt;any&gt;{
            const index = Number(contentId.value);
            if(index &lt;= this.videoList.length) {
                return Promise.resolve({content: this.videoList[index]});        
            } else {
                return Promise.resolve({});
            }
        }
    }
</code></pre>

<h3 id="create-composables">Create Composables</h3>

<ul>
  <li>
    <p>Create the <code>composables</code> directory at the root of your project.</p>
  </li>
  <li>
    <p>Create the <code>mystate.ts</code> file under the composables directory which will contain a state hook.</p>
  </li>
</ul>

<pre><code class="language-ts">    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    export function useMyState(initialState: any): any {
    const state = ref(initialState);
    const setState = (newState: any) =&gt; {
        state.value = newState;
    };
    
    return [readonly(state), setState];
    }
</code></pre>

<ul>
  <li>Create the <code>videoplayer.ts</code> file under the composables directory which will contain the video player hook using the capacitor-video-player.</li>
</ul>

<pre><code class="language-ts">    import { CapacitorVideoPlayer } from 'capacitor-video-player';
    import { Capacitor } from '@capacitor/core';

    export interface VideoPlayerOuput  {
        result?: boolean;
        method?: string;
        value?: any;
        message?: string;
    }

    interface PlayerData {
        mode: string,
        url: string,
        playerId: string,
        componentTag: string, 
        subtitle?: string | null,
        language?: string | null,
        subtitleOptions?: any | null,
        rate?: number | null,
        exitOnEnd?: boolean | null,
        loopOnEnd?: boolean | null,
        pipEnabled?: boolean | null,
        bkmodeEnabled?: boolean | null,
        showControls?: boolean | null,
        displayMode?: string | null,
        width?: number | null,
        height?: number | null
    }

    export interface VideoPlayerHook {
        echo: (value: string) =&gt; Promise&lt;{value: string}&gt;;
        initPlayer: (mode: string, url: string, playerId: string,
            componenTag: string, subTitleUrl?: string, 
            subTitleLangage?: string, subTitleOptions?: any, 
            rate?: number, exitOnEnd?: boolean, loopOnEnd?: boolean,
            pipEnabled?: boolean, bkmodeEnabled?: boolean,
            showControls?: boolean, displayMode?: string,
            width?:number, height?:number) =&gt; 
            Promise&lt;VideoPlayerOuput&gt;;
        isPlaying: (playerId: string) =&gt; Promise&lt;VideoPlayerOuput&gt;;
        pause: (playerId: string) =&gt; Promise&lt;VideoPlayerOuput&gt;;
        play: (playerId: string) =&gt; Promise&lt;VideoPlayerOuput&gt;;
        getDuration: (playerId: string) =&gt; Promise&lt;VideoPlayerOuput&gt;;
        setVolume: (playerId: string, volume: number) =&gt; 
            Promise&lt;VideoPlayerOuput&gt;;
        getVolume: (playerId: string) =&gt; Promise&lt;VideoPlayerOuput&gt;;
        setMuted: (playerId: string, muted: boolean) =&gt; 
            Promise&lt;VideoPlayerOuput&gt;;
        getMuted: (playerId: string) =&gt; Promise&lt;VideoPlayerOuput&gt;;
        setCurrentTime: (playerId: string, seektime: number) =&gt; 
            Promise&lt;VideoPlayerOuput&gt;;
        getCurrentTime: (playerId: string) =&gt; Promise&lt;VideoPlayerOuput&gt;;
        stopAllPlayers: () =&gt; Promise&lt;VideoPlayerOuput&gt;;
        removeListeners: () =&gt; Promise&lt;void&gt;;
        getPlatform: () =&gt; Promise&lt;{platform: string}&gt;;
    }

    export function useVideoPlayer(emit: (event: "onPlay" | "onPause" | "onEnded" | "onExit" | "onReady", ...args: any[]) =&gt; void): VideoPlayerHook {
        const platform = Capacitor.getPlatform();
        const vpPlugin: any = CapacitorVideoPlayer;
        let playListener: any;
        let pauseListener: any;
        let endedListener: any;
        let exitListener: any;
        let readyListener: any;
        
        /**
         * Add Listeners
         */
        const addListeners = async (): Promise&lt;void&gt; =&gt; {
            playListener = await vpPlugin.addListener('jeepCapVideoPlayerPlay',
                (e: any) =&gt; {
                    const fromPlayerId = e.fromPlayerId;
                    const currentTime = e.currentTime
                    emit('onPlay', {fromPlayerId, currentTime})
                }, false);
            pauseListener = await vpPlugin.addListener('jeepCapVideoPlayerPause',
                (e: any) =&gt; {
                    const fromPlayerId = e.fromPlayerId;
                    const currentTime = e.currentTime
                    emit('onPause', {fromPlayerId, currentTime})
                }, false);
            endedListener = await vpPlugin.addListener('jeepCapVideoPlayerEnded',
                (e: any) =&gt; {
                    const fromPlayerId = e.fromPlayerId;
                    const currentTime = e.currentTime
                    emit('onEnded', {fromPlayerId, currentTime})
                }, false);
            exitListener = await vpPlugin.addListener('jeepCapVideoPlayerExit',
                (e: any) =&gt; {
                    const dismiss = e.dismiss;
                    emit('onExit', {dismiss})
                },false);
            readyListener = await vpPlugin.addListener('jeepCapVideoPlayerReady',
                (e: any) =&gt; {
                    const fromPlayerId = e.fromPlayerId;
                    const currentTime = e.currentTime
                    emit('onReady', {fromPlayerId, currentTime})
                }, false);
        }
        /**
         * Remove Listeners
         */
        const removeListeners = async (): Promise&lt;void&gt; =&gt; {
            await playListener.remove();
            await pauseListener.remove();
            await endedListener.remove();
            await exitListener.remove();
            await readyListener.remove();
        };
        /**
         * Echo value
         * @param value 
         */
        const echo = async (value: string): Promise&lt;{value: string}&gt; =&gt; {
            const ret = {value: ""};
            if(value) {
                const r = await vpPlugin.echo(value);
                if(r) {
                    return r;
                }
                return ret;    
            } else {
                ret.value = "Echo: failed";
                return ret;
            }
        };
        /**
         * Get Platform
         */
        const getPlatform = async (): Promise&lt;any&gt; =&gt; {
            return {platform: platform};
        };
        /**
         * Method initPlayer
         * Init the player
         * @param mode 
         * @param url 
         * @param playerId 
         * @param componentTag 
         * @param subTitleUrl 
         * @param subTitleLanguage 
         * @param subTitleOptions 
         * @param width 
         * @param height 
         * @returns 
         */
        const initPlayer = async (mode: string, url : string,
            playerId: string, componentTag: string,
            subTitleUrl?: string , subTitleLanguage?: string, subTitleOptions?: any,
            rate?: number, exitOnEnd?: boolean, loopOnEnd?: boolean,
            pipEnabled?: boolean, bkmodeEnabled?: boolean,
            showControls?: boolean, displayMode?: string) =&gt; {
            const playerData: PlayerData = {mode: mode, url: url, 
                playerId: playerId, componentTag: componentTag}
            playerData.subtitle = subTitleUrl != null ? subTitleUrl : null; 
            playerData.language = subTitleLanguage != null ? subTitleLanguage : null;
            if(subTitleOptions != null) {
                playerData.subtitleOptions = {};
                if(subTitleOptions.backgroundColor != null)
                    playerData.subtitleOptions.backgroundColor = subTitleOptions.backgroundColor;
                if(subTitleOptions.fontSize != null)
                    playerData.subtitleOptions.fontSize = subTitleOptions.fontSize;
                if(subTitleOptions.foregroundColor != null)
                    playerData.subtitleOptions.foregroundColor = subTitleOptions.foregroundColor;
                
            } else {
                playerData.subtitleOptions = null;
            }
            playerData.rate = rate != null ? rate : 1; 
            playerData.exitOnEnd = exitOnEnd != null ? exitOnEnd : true; 
            playerData.loopOnEnd = loopOnEnd != null ? loopOnEnd : false; 
            playerData.pipEnabled = pipEnabled != null ? pipEnabled : true; 
            playerData.bkmodeEnabled = bkmodeEnabled != null ? bkmodeEnabled : true; 
            playerData.displayMode = displayMode != null ? displayMode : 'portrait'; 

            const r = await vpPlugin.initPlayer(playerData);
            if (r) {
                if( typeof r.result != 'undefined') {
                    return r;
                }
            }
            return {result: false, method: "initPlayer", 
                    message: "initPlayer failed"};
        }; 
        /**
         * Method isPlaying 
         * @param playerId string
         */
        const isPlaying = async (playerId: string) =&gt; {
            const r = await vpPlugin.isPlaying({ playerId:playerId });
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
            return { result: false, method: "isPlaying",
                message: "isPlaying failed" };

        };

        /**
         * Method pause 
         * pause the videoplayer 
         * @param playerId string
         */
        const pause = async (playerId: string) =&gt; {
            const r = await vpPlugin.pause({ playerId: playerId });
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
            return { result: false, method: "pause",
                message: "pause failed" };

        };

        /**
         * Method play 
         * play the videoplayer 
         * @param playerId string
         */
        const play = async (playerId: string) =&gt; {
            const r = await vpPlugin.play({ playerId: playerId });
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
            return { result: false, method: "play",
                message: "play failed" };

        };

        /**
         * Method getDuration 
         * get the video duration
         * @param playerId string
         */
        const getDuration = async (playerId: string) =&gt; {
            const r = await vpPlugin.getDuration({ 
                playerId: playerId });
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
            return { result: false, method: "getDuration",
                message: "getDuration failed" };

        };

        /**
         * Method setVolume 
         * set the video volume
         * @param playerId string
         * @param volume number
         */
        const setVolume = async (playerId: string,
                volume: number) =&gt; {
            const r = await vpPlugin.setVolume({ playerId: playerId,
                volume: volume });
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
            return { result: false, method: "setVolume",
                message: "setVolume failed" };

        };

        /**
         * Method getVolume 
         * get the video volume
         * @param playerId string
         */
        const getVolume = async (playerId: string) =&gt; {
            const r = await vpPlugin.getVolume({ 
                    playerId: playerId });
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
        return { result: false, method: "getVolume",
            message: "getVolume failed" };

        };

        /**
         * Method setMuted 
         * set the video muted parameter
         * @param playerId string
         * @param muted boolean
         */
        const setMuted = async (playerId: string,
                muted: boolean) =&gt; {
            const r = await vpPlugin.setMuted({ 
                    playerId: playerId, muted: muted });
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
            return { result: false, method: "setMuted",
                message: "setMuted failed" };

        };

        /**
         * Method getMuted 
         * get the video muted parameter
         * @param playerId string
         */
        const getMuted = async (playerId: string) =&gt; {
            const r = await vpPlugin.getMuted({ playerId: playerId });
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
            return { result: false, method: "getMuted",
                message: "getMuted failed" };

        };

        /**
         * Method setCurrentTime 
         * set the video current time
         * @param playerId string
         * @param seektime number
         */
        const setCurrentTime = async (playerId: string,
                    seektime: number) =&gt; {
            const r = await vpPlugin.setCurrentTime({ 
                playerId: playerId, seektime: seektime });
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
            return { result: false, method: "setCurrentTime",
                message: "setCurrentTime failed" };

        };

        /**
         * Method getCurrentTime 
         * get the video current time
         * @param playerId string
         */
        const getCurrentTime = async (playerId: string) =&gt; {
            const r = await vpPlugin.getCurrentTime({ 
                playerId: playerId });
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
            return { result: false, method: "getCurrentTime",
                message: "getCurrentTime failed" };

        };

        /**
         * Method stopAllPlayers
         * stop all players
         */
        const stopAllPlayers = async () =&gt; {
            const r = await vpPlugin.stopAllPlayers();
            if (r) {
                if (typeof r.result != 'undefined') {
                    return r;
                }
            }
            return { result: false, method: "stopAllPlayers",
                message: "stopAllPlayers failed" };

        };

        // Add Listeners
        addListeners();
        
        return { echo, initPlayer, isPlaying, play, pause, getDuration,
            setVolume, getVolume, setMuted, getMuted, setCurrentTime, 
            getCurrentTime, stopAllPlayers, removeListeners, getPlatform };
    }
</code></pre>

<h3 id="create-fullscreenvideoplayer-component">Create FullscreenVideoPlayer Component</h3>

<p>This component will play the video by using the video player hook.
In the <code>components</code> directory, create the <code>FullscreenVideoPlayer.vue</code> file and copy the following.</p>

<pre><code class="language-ts">    &lt;template&gt;
    &lt;div id="fullscreen"&gt;
    &lt;/div&gt;
    &lt;/template&gt;
    &lt;script lang="ts"&gt;
    export default defineNuxtComponent({
        name: 'FullscreenVideoPlayer',
        props: ['videoData'],
        emits: ['onPlay','onPause','onEnded', 'onExit','onReady'],
        setup(props, { emit }) {
        let ret: any = {};
        let params: any[] = [];
        const vpHook: VideoPlayerHook = useVideoPlayer(emit);
        const playVideo = async () =&gt; {
            params = [];
    
            if( props.videoData.subtitle_url != null &amp;&amp; 
                props.videoData.subtitle_langage != null) {
            params = [...params,props.videoData.subtitle_url,props.videoData.subtitle_langage];
            }
            if(props.videoData.subtitle_options != null) {
            params = [...params,props.videoData.subtitle_options];
            }
            const args: any[] = [...params];
            ret = await vpHook.initPlayer("fullscreen",props.videoData.url,"fullscreen","div",...params);
            console.log(`ret : ${JSON.stringify(ret)}`)

        } 
        onMounted(async () =&gt; {
            await playVideo();
        });
        onUnmounted(async () =&gt; {
            await vpHook.removeListeners();
            await vpHook.stopAllPlayers();
        });
        }
    });
    &lt;/script&gt;
</code></pre>

<h3 id="create-viewer-video-page">Create Viewer Video Page</h3>

<p>This page will use the <code>FullscreenVideoPlayer</code> vue component based on the index of the video in the videoList.</p>

<ul>
  <li>
    <p>Create the <code>viewervideo</code> directory under the <code>pages</code> directory.</p>
  </li>
  <li>
    <p>Create the <code>[id].vue</code> page under the <code>viewervideo</code> directory, and copy the following code.</p>
  </li>
</ul>

<pre><code class="language-ts">    &lt;template&gt;
    &lt;div id="viewervideo-page"&gt;
        &lt;header&gt;
            &lt;PageHeader :title="pageTitle"&gt;&lt;/PageHeader&gt;
        &lt;/header&gt;
        &lt;div id="viewervideo-container"&gt;
            &lt;van-grid :border="false" :column-num="1"&gt;
                &lt;van-grid-item class="viewervideo-publish"&gt;
                    &lt;p class="viewervideo-publish-date"&gt;
                    
                    &lt;/p&gt;
                    &lt;h2 class="viewervideo-publish-title"&gt;&lt;/h2&gt;
                &lt;/van-grid-item&gt;
                &lt;van-grid-item&gt;
                    &lt;span class="viewervideo-publish-description"&gt;&lt;/span&gt;
                &lt;/van-grid-item&gt;
                &lt;van-grid-item&gt;
                    &lt;van-button type="primary" block @click="playVideo()"&gt;
                        Watch
                    &lt;/van-button&gt;
                &lt;/van-grid-item&gt;
            &lt;/van-grid&gt;
            &lt;div v-if="isClicked"&gt;
                &lt;FullscreenVideoPlayer @onPlay="handleOnPlay" @onPause="handleOnPause" @onEnded="handleOnEnded" @onExit="handleOnExit" @onReady="handleOnReady" :videoData="videoContent"&gt;&lt;/FullscreenVideoPlayer&gt;
            &lt;/div&gt;

        &lt;/div&gt; 
    &lt;/div&gt; 
    &lt;/template&gt;
    &lt;script lang="ts"&gt;
    import VideoService from '@/services/video.service';
    import type { VideoModel } from '~/interfaces/interfaces';
    export default defineNuxtComponent({
    name: "ViewerVideoPage",
    alias: "/viewervideo",
    setup() {
        // get the props id
        const route = useRoute();
        // build-up the page  title
        const videoRef = ref(route.params.id);
        const videoText = computed(() =&gt; {
            if(Number(videoRef.value) == 0) {
                return "MP4 Video"
            }
            if(Number(videoRef.value) == 1) {
                return "HLS Video"
            }
        });
        const pageTitle = `${videoText.value}`
        const videoService = new VideoService();
        const [isClicked, setIsClicked] = useMyState(false);
        const playerLeave = async () =&gt; {
            console.log (`&gt;&gt;&gt; in [id].vue playerLeave`)
            setIsClicked(false);
        }
        const handleOnPlay = (e:any) =&gt; {
            console.log(`&lt;&lt;&lt;&lt; onPlay in ViewerVideo ${e.fromPlayerId} ct: ${e.currentTime}`);
        }
        const handleOnPause = (e:any) =&gt; {
            console.log(`&lt;&lt;&lt;&lt; onPause in ViewerVideo ${e.fromPlayerId} ct: ${e.currentTime}`)
        }
        const handleOnEnded = (e:any) =&gt; {
            console.log(`&lt;&lt;&lt;&lt; onEnded in ViewerVideo ${e.fromPlayerId} ct: ${e.currentTime}`)
            playerLeave();
        }
        const handleOnExit = (e:any) =&gt; {
            console.log(`&lt;&lt;&lt;&lt; onExit in ViewerVideo ${e.dismiss}`)
            playerLeave();
        }
        const handleOnReady = (e:any) =&gt; {
            console.log(`&lt;&lt;&lt;&lt; onReady in ViewerVideo ${e.fromPlayerId} ct: ${e.currentTime}`)
        }
        
        const videoContent = ref({} as VideoModel);

        const getVideoContent = async () =&gt; {
            const response = await videoService.get(videoRef);
            if ("content" in response) {
                videoContent.value = response.content;
            } else {
                console.log("Failed to load content");
                throw new Error("Failed to load content")
            }    
        }
        onMounted(async () =&gt; {
            await getVideoContent();
        });

        return {pageTitle, isClicked, setIsClicked, videoContent, handleOnPlay,
                handleOnPause, handleOnEnded, handleOnExit, handleOnReady};
    },
    computed: {
        prettyPublishedAt() {
        const strDate: string = this.videoContent.published_at;
        const d = new Date(strDate);
        return d.toLocaleString(undefined, {
            year: "numeric",
            month: "long",
            day: "numeric",
        });
        
        },
    },
    methods: {
        async playVideo() {
            this.setIsClicked(true);
        },
    }
    });
    &lt;/script&gt;
    &lt;style scoped&gt;
    #viewervideo-page {
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    display: flex;
    position: absolute; 
    z-index: 1;  
    }
    #viewervideo-container {
    position: absolute;
    top: 96px;
    left: 0;
    right: 0;
    bottom: 0;
    }
    .viewervideo-publish {
    display:flex;
    flex-direction: row;
    }
    .viewervideo-publish-date {
    margin-top:3px;
    margin-bottom:3px;
    }
    .viewervideo-publish-title {
    margin-top:3px;
    margin-bottom:3px;
    }
    .viewervideo-publish-description {
    margin-top:3px;
    margin-bottom:3px;
    }

    &lt;/style&gt; 
</code></pre>

<h3 id="reference-the-videoviewer-page-in-index-page">Reference the VideoViewer Page in Index Page</h3>

<ul>
  <li>open the <code>index.vue</code> file  and add the following lines afterthe <code>van-grid-item</code> containing the link to the <code>about</code> page.</li>
</ul>

<pre><code class="language-html">    &lt;van-grid-item&gt;
        &lt;NuxtLink to="/viewervideo/0" class="n-link-base"&gt;
            MP4 Video
        &lt;/NuxtLink&gt;
    &lt;/van-grid-item&gt;
    &lt;van-grid-item&gt;
        &lt;NuxtLink to="/viewervideo/1" class="n-link-base"&gt;
            HLS Video
        &lt;/NuxtLink&gt;
    &lt;/van-grid-item&gt;
</code></pre>

<h3 id="run-the-application-in-the-web-browser">Run the Application in the Web Browser</h3>

<ul>
  <li>Execute the following command.</li>
</ul>

<pre><code class="language-bash"> npm run dev
</code></pre>
<ul>
  <li>
    <p>Open http://localhost:3000/ in your favorite browser.</p>
  </li>
  <li>
    <p>Screenshot of the <code>Home</code> Page screen:</p>
  </li>
</ul>

<div align="center"><br /><img src="/images/Vant-Nuxt-VideoPlayer-Home.png" width="50%" /></div>
<p><br /></p>

<ul>
  <li>
    <p>Click on the <code>MP4 Video</code> link to go to the MP4 Video page.</p>
  </li>
  <li>
    <p>Screenshot of the <code>MP4 Video</code> screen:</p>
  </li>
</ul>

<div align="center"><br /><img src="/images/Vant-Nuxt-VideoPlayer-MP4.png" width="50%" /></div>
<p><br /></p>

<ul>
  <li>Click on <code>Watch</code> button and the video will start playing fullscreen.</li>
</ul>

<p>Congratulations, the Web part of the application is now working</p>

<h3 id="run-the-application-in-ios-device">Run the Application in iOS Device</h3>

<ul>
  <li>Execute the following commands.</li>
</ul>

<pre><code class="language-bash"> npm i --save @capacitor/ios
 npm run generate
 npx cap add ios
 npx cap copy
 npx cap open ios
</code></pre>

<h3 id="run-the-application-in-android-device">Run the Application in Android Device</h3>

<ul>
  <li>Execute the following commands.</li>
</ul>

<pre><code class="language-bash"> npm i --save @capacitor/android
 npm run generate
 npx cap add android
 npx cap copy
 npx cap open android
</code></pre>
<ul>
  <li>In AndroidStudio got to Preferences-&gt;Build,Execution,Deployment-&gt;Build Tools-&gt;Gradle
    <ul>
      <li>modify Gradle JDK to <code>17 Oracle OpenJDK version 17.0.7</code>.</li>
      <li>click on <code>Apply</code>and <code>OK</code>.</li>
    </ul>
  </li>
  <li>Add these lines in the <code>AndroidManifest.xml</code> file</li>
</ul>

<pre><code class="language-xml">    &lt;meta-data
        android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
        android:value="com.google.android.exoplayer2.ext.cast.DefaultCastOptionsProvider"&gt;
    &lt;/meta-data&gt;
</code></pre>

<p>and</p>

<pre><code class="language-xml">     &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32"/&gt;
</code></pre>

<ul>
  <li>Add this dependency in the <code>build.gradle(Project: android)</code> file under dependencies</li>
</ul>

<pre><code class="language-xml">    classpath 'com.google.gms:google-services:4.4.0'
</code></pre>

<ul>
  <li>Add this implementation in the <code>build.gradle(Module: app)</code>file under dependencies</li>
</ul>

<pre><code class="language-xml">     implementation 'com.google.android.gms:play-services-cast-framework:21.3.0'
</code></pre>

<ul>
  <li>In <code>variables.gradle</code> file modify</li>
</ul>

<pre><code class="language-xml"> coreSplashScreenVersion = '1.0.1'
</code></pre>
<ul>
  <li>Go to File-&gt;Sync Project with Gradle files.</li>
</ul>

<h3 id="conclusion">Conclusion</h3>

<p>We have completed the Vant Nuxt Capacitor Video Player Example Tutorial using Nuxt, Vant and the capacitor-video-player plugin.</p>

<p>We learned how to implement the <code>capacitor-video-player</code> plugin in the Nuxt Framework using Vant, a lightweight, customizable Vue UI library, and Ionic Capacitor which add native functionality.</p>

<p>Enjoy your development from there.</p>]]></content><author><name>Quéau Jean Pierre</name></author><category term="Other" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">SQLite Database Encryption using the @capacitor-community/sqlite plugin</title><link href="https://jepiqueau.github.io/2023/10/06/SQLite-Database-Encryption.html" rel="alternate" type="text/html" title="SQLite Database Encryption using the @capacitor-community/sqlite plugin" /><published>2023-10-06T00:00:00+00:00</published><updated>2023-10-06T00:00:00+00:00</updated><id>https://jepiqueau.github.io/2023/10/06/SQLite-Database-Encryption</id><content type="html" xml:base="https://jepiqueau.github.io/2023/10/06/SQLite-Database-Encryption.html"><![CDATA[<hr />

<p><em>last updated on November 6, 2023 by Quéau Jean Pierre</em></p>

<p>In that tutorial we will learned how to <code>encrypt</code> existing or new SQLite databases using the @capacitor-community/sqlite plugin.</p>

<p>The process flow described here does not depend on the <code>framework</code> you are using to develop your application.</p>

<p>The @capacitor-community/sqlite plugin enables database encryption for applications that run natively on iOS, Android, and Electron devices.</p>

<h2 id="table-of-contents">Table of Contents</h2>

<hr />
<ul>
  <li><a href="#process-flow">Process Flow</a>
    <ul>
      <li><a href="#isencryption">IsEncryption</a></li>
      <li><a href="#set-encryption-passphrase">Set Encryption Passphrase</a></li>
      <li><a href="#opendatabase-method-in-sqliteservice">OpenDatabase Method in sqliteService</a></li>
      <li><a href="#your-database-service">Your Database Service</a></li>
    </ul>
  </li>
  <li><a href="#others-methods-when-necessary">Others Methods When Necessary</a>
    <ul>
      <li><a href="#is-secretpassphrase-stored-required">Is Secret/Passphrase Stored (Required)</a></li>
      <li><a href="#is-passphrase-valid-optional">Is Passphrase Valid (Optional)</a></li>
      <li><a href="#change-encryption-secret-optional">Change Encryption Secret (Optional)</a></li>
      <li><a href="#clear-encryption-passphrase-optional">Clear Encryption Passphrase (Optional)</a></li>
      <li><a href="#decrypt-all-databases-optional">Decrypt All Databases (Optional)</a></li>
      <li><a href="#get-database-list-optional">Get Database List (Optional)</a></li>
      <li><a href="#is-database-encrypted">Is Database Encrypted</a></li>
    </ul>
  </li>
  <li><a href="#conclusion">Conclusion</a></li>
</ul>

<hr />

<h2 id="process-flow">Process Flow</h2>

<h3 id="isencryption">IsEncryption</h3>

<ul>
  <li>Set the deviceIsEncryption to true in capacitor.config.ts file.
    <pre><code class="language-ts"> const config: CapacitorConfig = {
 ...
     plugins: {
         CapacitorSQLite: {
             ...
             iosIsEncryption: true,
             ...
             androidIsEncryption: true,
             ...
             electronIsEncryption: true,
             ...
         }
     }
 ...
 }
</code></pre>
  </li>
  <li>
    <p>Add <code>isDeviceEncryption</code> method in the <code>sqliteService.ts</code> file:</p>

    <pre><code class="language-ts"> export interface ISQLiteService {
     ...
     isDeviceEncryption(): Promise&lt;boolean&gt;
 };    
</code></pre>

    <pre><code class="language-ts"> class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     ... 

     async isDeviceEncryption(): Promise&lt;boolean&gt; { 
         // Is platform allow for encryption
         const isPlatformEncryption = this.platform === 'web' ? false : true;
         // Check if isEncryption in the capacitor.config.ts
         const isEncryptInConfig = (await this.sqliteConnection.isInConfigEncryption()).result

         return isPlatformEncryption &amp;&amp; isEncryptInConfig ? true : false;
     }
 }
</code></pre>
  </li>
</ul>

<h3 id="set-encryption-passphrase">Set Encryption Passphrase</h3>

<ul>
  <li>
    <p>This methods allows to set the <code>passphrase</code> which is required to encrypt databases.</p>
  </li>
  <li>
    <p>Add <code>setEncryptionPassphrase</code> method in the <code>sqliteService.ts</code> file:</p>

    <pre><code class="language-ts"> export interface ISQLiteService {
     ...
     setEncryptionPassphrase(passphrase: string): Promise&lt;void&gt;
 };    
</code></pre>

    <pre><code class="language-ts"> class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     ... 

     async setEncryptionPassphrase(passphrase: string): Promise&lt;void&gt; {
         // check if a passphrase is already stored
         let isSetPassphrase = await this.isSecretStored();
         if(isSetPassphrase) {
             const msg = "Passphrase already stored";
             throw new Error(`sqliteService.setEncryptionPassphrase: ${msg}`);
         }
         return Promise.resolve(await this.sqliteConnection.setEncryptionSecret(passphrase));
     }
     ... 
 }
</code></pre>
  </li>
</ul>

<h3 id="opendatabase-method-in-sqliteservice">OpenDatabase Method in sqliteService</h3>

<ul>
  <li>This method will allow to:
    <ul>
      <li>create/open a non-encrypted database</li>
      <li>create/open an encrypted database</li>
      <li>open a non-encrypted database and encrypt it</li>
      <li>open an encrypted database and decrypt it</li>
    </ul>
  </li>
  <li>create or modify <code>openDatabase</code> method in the <code>sqliteService.ts</code> file as followed:
    <pre><code class="language-ts"> export interface ISQLiteService {
     ...
 openDatabase(dbName:string, version: number,
              readOnly: boolean, decrypt?: boolean)
             : Promise&lt;SQLiteDBConnection&gt;;
 };    
</code></pre>

    <pre><code class="language-ts"> class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     ... 

 async openDatabase(dbName:string, version: number,
                    readOnly: boolean,
                    decrypt: boolean = false)
             : Promise&lt;SQLiteDBConnection&gt;  {
     this.dbNameVersionDict.set(dbName, version);
     let db: SQLiteDBConnection;
     const retCC = (await this.sqliteConnection.checkConnectionsConsistency()).result;
     let isConn = (await this.sqliteConnection.isConnection(dbName, readOnly)).result;
     if(retCC &amp;&amp; isConn) {
         db = await this.sqliteConnection.retrieveConnection(dbName, readOnly);
     } else {
         let encrypted = false;
         let mode = "no-encryption";
         if(this.platform !== "web") {
             const isDbExists = (await this.sqliteConnection.isDatabase(dbName)).result!;
             const isDevEncrypt = await this.isDeviceEncryption();
             const isDbEncrypt = isDevEncrypt &amp;&amp; isDbExists
                     ? (await this.sqliteConnection.isDatabaseEncrypted(dbName)).result!
                     : false;
             const isPassphrase = isDevEncrypt 
                     ? await this.isSecretStored()
                     : false;
             encrypted = (!isDbExists &amp;&amp; isDevEncrypt &amp;&amp; isPassphrase) ||
                          (isDbExists &amp;&amp; isDevEncrypt &amp;&amp; isDbEncrypt &amp;&amp; isPassphrase) ||
                          (isDbExists &amp;&amp; isDevEncrypt &amp;&amp; !isDbEncrypt &amp;&amp; isPassphrase ) ? true : false;
             mode =  isDbExists &amp;&amp; isDevEncrypt &amp;&amp; !isDbEncrypt &amp;&amp; isPassphrase
                         ? "encryption" 
                         : encrypted &amp;&amp; decrypt ? "decryption"
                         : encrypted ? "secret" : "no-encryption";
         }
         db = await this.sqliteConnection
                 .createConnection(dbName, encrypted, mode, version, readOnly);
     }
    
     await db.open();
     const res = (await db.isDBOpen()).result;
     if(res) {
         return db;
     } else {
         const msg = "database not opened";
         throw new Error(`sqliteService.openDatabase: ${msg}`);
     }

 }
</code></pre>
  </li>
</ul>

<h3 id="your-database-service">Your Database Service</h3>

<ul>
  <li>
    <p>In <code>initializeDatabase</code> method or whatever you have call them, replace the call of sqliteServ.openDatabase with:</p>

    <pre><code class="language-ts"> this.db = await this.sqliteServ.openDatabase(this.database,
                                              this.loadToVersion,
                                              false);
</code></pre>

    <p>here understand <code>this.database</code> as the database name and <code>this.loadToVersion</code> as the database version.</p>
  </li>
</ul>

<h2 id="others-methods-when-necessary">Others Methods When Necessary</h2>

<h3 id="is-secretpassphrase-stored-required">Is Secret/Passphrase Stored (Required)</h3>

<ul>
  <li>
    <p>This method allows to know if a <code>passphrase</code> is already stored for your application.</p>
  </li>
  <li>
    <p>Add <code>isSecretStored</code> method in the <code>sqliteService.ts</code> file:</p>

    <pre><code class="language-ts"> export interface ISQLiteService {
     ...
     isSecretStored(): Promise&lt;boolean&gt;;
 };    
</code></pre>

    <pre><code class="language-ts"> class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     ... 

     async isSecretStored(): Promise&lt;boolean&gt; {
         const res = await this.sqliteConnection.isSecretStored()
         return  res.result ?? false;
     }

     ... 

 }
</code></pre>
  </li>
</ul>

<h3 id="is-passphrase-valid-optional">Is Passphrase Valid (Optional)</h3>

<ul>
  <li>
    <p>This method allow to check if a given passphrase is equal to the one stored</p>
  </li>
  <li>
    <p>Add <code>isPassphraseValid</code> method in the <code>sqliteService.ts</code> file:</p>

    <pre><code class="language-ts"> export interface ISQLiteService {
     ...
     isPassphraseValid(passphrase: string): Promise&lt;boolean&gt;;
 };    
</code></pre>

    <pre><code class="language-ts"> class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     ... 

     async isPassphraseValid(passphrase: string): Promise&lt;boolean&gt; {
         const res = await this.sqliteConnection.checkEncryptionSecret(passphrase);
         return  res.result ?? false;
     }

     ... 

 }
</code></pre>
  </li>
</ul>

<h3 id="change-encryption-secret-optional">Change Encryption Secret (Optional)</h3>

<ul>
  <li>
    <p>This method allow to change the stored passphrase with a new one</p>
  </li>
  <li>
    <p>Add <code>changeEncryptionSecret</code> method in the <code>sqliteService.ts</code> file:</p>

    <pre><code class="language-ts"> export interface ISQLiteService {
     ...
     changeEncryptionSecret(passphrase: string, oldpassphrase: string)
                                                     : Promise&lt;void&gt;
 };    
</code></pre>

    <pre><code class="language-ts"> class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     ... 

     async changeEncryptionSecret(passphrase: string,
                                  oldpassphrase: string)
                                  : Promise&lt;void&gt; {
         return await this.sqliteConnection.changeEncryptionSecret(
                                         passphrase, oldpassphrase);
     }
    
     ... 

 }
</code></pre>
  </li>
</ul>

<h3 id="clear-encryption-passphrase-optional">Clear Encryption Passphrase (Optional)</h3>

<ul>
  <li>
    <p>This method allow to clear the stored passphrase</p>
  </li>
  <li>
    <p>Add <code>clearEncryptionPassphrase</code> method in the <code>sqliteService.ts</code> file:</p>

    <pre><code class="language-ts"> export interface ISQLiteService {
     ...
     clearEncryptionPassphrase(): Promise&lt;void&gt;;
 };    
</code></pre>

    <pre><code class="language-ts"> class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     ... 

     async clearEncryptionPassphrase(): Promise&lt;void&gt; {
         // close all open connections
         await this.sqliteConnection.closeAllConnections();
         return await this.sqliteConnection.clearEncryptionSecret();
     }
   
     ... 

 }
</code></pre>
  </li>
</ul>

<h3 id="decrypt-all-databases-optional">Decrypt All Databases (Optional)</h3>

<ul>
  <li>
    <p>This method allow to decrypt all databases in the database folder</p>
  </li>
  <li>
    <p>Add <code>decryptAllDatabases</code> method in the <code>sqliteService.ts</code> file:</p>

    <pre><code class="language-ts"> export interface ISQLiteService {
     ...
     decryptAllDatabases(dbVerDict: Map&lt;string, number&gt;): Promise&lt;void&gt;;
 };    
</code></pre>

    <pre><code class="language-ts"> class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     ... 

     async decryptAllDatabases(dbVerDict: Map&lt;string, number&gt;): Promise&lt;void&gt; {

         // close all open connections
         await this.sqliteConnection.closeAllConnections();
         // get the database list
         const dbList = await this.getDatabaseList();
         const encryptNames = dbList.filter(item =&gt; item.encrypted === true).map(item =&gt; item.name);
         for (const name of encryptNames) {
             const version = dbVerDict.get(name) ?? 1;
             // decrypt the database
             await this.openDatabase(name, version, false, true);
         }
         // close all open connections
         await this.sqliteConnection.closeAllConnections();
         // clear the passphrase
         await this.sqliteConnection.clearEncryptionSecret();
     }
    
     ... 

 }
</code></pre>
  </li>
</ul>

<h3 id="get-database-list-optional">Get Database List (Optional)</h3>

<ul>
  <li>
    <p>This method allow to get the list of all databases in the database folder</p>
  </li>
  <li>
    <p>Add <code>getDatabaseList</code> method in the <code>sqliteService.ts</code> file:</p>

    <pre><code class="language-ts"> export interface ISQLiteService {
     ...
     getDatabaseList(): Promise&lt;any[]&gt;;
 };    
</code></pre>

    <pre><code class="language-ts"> class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     ... 

     async getDatabaseList(): Promise&lt;any[]&gt; {
         const retDbList: TDatabase[] = [];
         const dbList = (await this.sqliteConnection.getDatabaseList()).values!;
         if(dbList.length &gt; 0) {
             for (let idx:number = 0; idx &lt; dbList.length; idx++) {
                 const dbName = dbList[idx].split("SQLite.db")[0];
                 const isEncrypt = (await this.sqliteConnection.isDatabaseEncrypted(dbName)).result!;
                 const data: TDatabase = {name: dbName, encrypted: isEncrypt};
                 retDbList.push(data);
             }
         }
         return retDbList;
     };
        
     ... 

 }
</code></pre>
  </li>
</ul>

<h3 id="is-database-encrypted">Is Database Encrypted</h3>

<ul>
  <li>
    <p>This methods allows to check if a database exists and is encrypted</p>
  </li>
  <li>
    <p>Add <code>isDatabaseEncrypted</code> method in the <code>sqliteService.ts</code> file:</p>

    <pre><code class="language-ts"> async isDatabaseEncrypted(dbName: string): Promise&lt;boolean&gt; {
     if((await this.sqliteConnection.isDatabase(dbName)).result)  {
         const isDBEncrypted = (await this.sqliteConnection.isDatabaseEncrypted(dbName)).result;
         return isDBEncrypted!
     } else {
         const msg = `database ${dbName} does not exist` ;
         throw new Error(`sqliteService.isDatabaseEncrypted: ${msg}`);
     }       
 }
</code></pre>
  </li>
</ul>

<h2 id="conclusion">Conclusion</h2>

<p>We have completed SQLite Database Encryption using the <code>@capacitor-community/sqlite plugin</code>.</p>

<p>We learned about the process flow required to encrypt the database</p>
<ul>
  <li>by first modifying the <code>capacitor.config.ts</code> file,</li>
  <li>set the encryption passphrase in the sqliteService</li>
  <li>then how to open the database in the sqliteService</li>
  <li>call the sqliteService openDatabase from your own service or compon
ent.</li>
</ul>

<p>We learned how to enhance the sqliteService with some methods that you may need during your application Development.</p>

<p>All this learning is not Framework dependent</p>

<p>An example for the Vue Framework can be found  at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/SQLite/Encryption/ionic7-vue-sqlite-app-encryption">Encryption/ionic7-vue-sqlite-app-encryption</a></p>]]></content><author><name>Quéau Jean Pierre</name></author><category term="Other" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Ionic 7 SQLite Database CRUD App Example Tutorial using Vue3 and @capacitor-community/sqlite</title><link href="https://jepiqueau.github.io/2023/09/05/Ionic7Vue-SQLite-CRUD-App.html" rel="alternate" type="text/html" title="Ionic 7 SQLite Database CRUD App Example Tutorial using Vue3 and @capacitor-community/sqlite" /><published>2023-09-05T00:00:00+00:00</published><updated>2023-09-05T00:00:00+00:00</updated><id>https://jepiqueau.github.io/2023/09/05/Ionic7Vue-SQLite-CRUD-App</id><content type="html" xml:base="https://jepiqueau.github.io/2023/09/05/Ionic7Vue-SQLite-CRUD-App.html"><![CDATA[<hr />

<p><em>last updated on November 6, 2023 by Quéau Jean Pierre</em></p>

<p>In that tutorial we will learned how to create a Ionic7/Vue basic CRUD application and implement the @capacitor-community/sqlite plugin to store the data in a SQLite database.</p>

<p>The first part of the tutorial will concentrate on how to create that application and run it on a Web browser where the data will be stored on an Indexed database using sql.js and localForage modules.
Go to <a href="#part-1---web---table-of-contents">Part 1 - Web - Table of Contents</a></p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/SQLite/Part-1/ionic7-vue-sqlite-app">Part-1/ionic7-vue-sqlite-app</a></p>

<p>Thanks to the Ionic Team and their hard work to bring CAPACITOR 5, the second part will concentrate on native platforms (iOS and Android) and also on Electron platform.
Go to <a href="#part-2---native---table-of-contents">Part 2 - Native - Table of Contents</a></p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/SQLite/Part-2/ionic7-vue-sqlite-app">Part-2/ionic7-vue-sqlite-app</a></p>

<h2 id="part-1---web---table-of-contents">Part 1 - Web - Table of Contents</h2>

<hr />
<ul>
  <li><a href="#install-new-ionic-application">Install New Ionic Application</a></li>
  <li><a href="#install-required-packages">Install Required Packages</a></li>
  <li><a href="#create-the-sqlite-database">Create the SQLite Database</a></li>
  <li><a href="#create-crud-and-sqlite-services">Create CRUD and SQLite Services</a></li>
  <li><a href="#vue-plugin-implementation">Vue Plugin Implementation</a></li>
  <li><a href="#users-page-implementation">Users Page Implementation</a></li>
  <li><a href="#users-component-implementation">Users Component Implementation</a></li>
  <li><a href="#modify-the-home-page">Modify the Home Page</a></li>
  <li><a href="#add-a-menu-to-the-app">Add a Menu to the App</a></li>
  <li><a href="#update-config-and-packagejson-scripts">Update Config and Package.json Scripts</a></li>
  <li><a href="#run-the-web-sqlite-app">Run the Web SQLite App</a></li>
  <li><a href="#part-1-conclusion">Part 1 Conclusion</a></li>
</ul>

<hr />

<h3 id="install-new-ionic-application">Install New Ionic Application</h3>

<ul>
  <li>
    <p>Install the latest version of Ionic CLI globally installed on your device, run the below command.</p>

    <pre><code class="language-bash"> sudo npm install -g @ionic/cli
</code></pre>
  </li>
  <li>
    <p>Create a new blank Ionic Vue app</p>

    <pre><code class="language-bash"> ionic start ionic7-vue-sqlite-app blank --type=vue --capacitor
</code></pre>
  </li>
  <li>
    <p>Go inside the project folder</p>

    <pre><code class="language-bash"> cd ./ionic7-vue-sqlite-app
</code></pre>
  </li>
</ul>

<h3 id="install-required-packages">Install Required Packages</h3>

<ul>
  <li>
    <p>run the below commands</p>

    <pre><code class="language-bash"> npm install --save @capacitor-community/sqlite
 npm install --save @capacitor/toast
 npm install --save @ionic/pwa-elements
 npm install --save-dev copyfiles
</code></pre>
  </li>
</ul>

<h3 id="create-the-sqlite-database">Create the SQLite Database</h3>

<ul>
  <li>
    <p>To easily upgrade the database from one version to the next, the database is created through an upgrade statement. In your editor, create a folder <code>upgrades</code> under the <code>src</code> folder and then create a new file <code>upgrades/user.upgrade.statements.ts</code>.</p>
  </li>
  <li>
    <p>Define the upgrade statements in <code>upgrades/user.upgrade.statements.ts</code> file</p>

    <pre><code class="language-ts"> export const UserUpgradeStatements = [
     {
     toVersion: 1,
     statements: [
         `CREATE TABLE IF NOT EXISTS users (
         id INTEGER PRIMARY KEY AUTOINCREMENT,
         name TEXT NOT NULL,
         active INTEGER DEFAULT 1
         );`
     ]
     },
     /* add new statements below for next database version when required*/
     /*
     {
     toVersion: 2,
     statements: [
         `ALTER TABLE users ADD COLUMN email TEXT;`,
     ]
     },
     */
 ]
   
</code></pre>
  </li>
  <li>
    <p>Define the User Model</p>

    <p>In your editor, create a folder <code>models</code> under the <code>src</code> folder and then create a new file <code>models/user.ts</code>.</p>
  </li>
  <li>
    <p>Update the <code>models/user.ts</code> file as</p>

    <pre><code class="language-ts"> export interface User {
     id: number
     name: string
     active: number
     /* for version 2
     email: string
     */
 }
</code></pre>
  </li>
</ul>

<h3 id="create-crud-and-sqlite-services">Create CRUD and SQLite Services</h3>

<ul>
  <li>
    <p>To create CRUD and SQLite services, in your file editor, add a new <code>src/services</code> folder and create the two following files:</p>

    <ul>
      <li><code>services/sqliteService.ts</code></li>
      <li><code>services/storageService.ts</code></li>
    </ul>
  </li>
  <li>
    <p>Open the <code>services/sqliteService.ts</code> file and replace with the following code.</p>

    <pre><code class="language-ts"> import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection, capSQLiteUpgradeOptions } from '@capacitor-community/sqlite';
 import { Capacitor } from '@capacitor/core';

 export interface ISQLiteService {
     getPlatform(): string
     initWebStore(): Promise&lt;void&gt;
     addUpgradeStatement(options: capSQLiteUpgradeOptions): Promise&lt;void&gt; 
     openDatabase(dbName: string, loadToVersion: number, readOnly: boolean): Promise&lt;SQLiteDBConnection&gt; 
     closeDatabase(dbName: string, readOnly: boolean): Promise&lt;void&gt;
     saveToStore(dbName: string): Promise&lt;void&gt;
     saveToLocalDisk(dbName: string): Promise&lt;void&gt;
     isConnection(dbName: string, readOnly: boolean): Promise&lt;boolean&gt;
 };

 class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     getPlatform(): string {
         return this.platform;
     }
     async initWebStore() : Promise&lt;void&gt;  {
         try {
             await this.sqliteConnection.initWebStore();
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.initWebStore: ${msg}`);
         }
         return;
     }
     async addUpgradeStatement(options: capSQLiteUpgradeOptions): Promise&lt;void&gt; {
         try {
             await this.sqlitePlugin.addUpgradeStatement(options);
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.addUpgradeStatement: ${msg}`);
         }
         return;
     }
     async openDatabase(dbName:string, loadToVersion: number,
                 readOnly: boolean): Promise&lt;SQLiteDBConnection&gt;  {
         this.dbNameVersionDict.set(dbName, loadToVersion);
         let encrypted = false;
         const mode = encrypted ? "secret" : "no-encryption";
         try {
             let db: SQLiteDBConnection;
             const retCC = (await this.sqliteConnection.checkConnectionsConsistency()).result;
             let isConn = (await this.sqliteConnection.isConnection(dbName, readOnly)).result;
             if(retCC &amp;&amp; isConn) {
             db = await this.sqliteConnection.retrieveConnection(dbName, readOnly);
             } else {
                 db = await this.sqliteConnection
                         .createConnection(dbName, encrypted, mode, loadToVersion, readOnly);
             }
             const jeepSQlEL = document.querySelector("jeep-sqlite")
        
             await db.open();
             const res = await db.isDBOpen();
             return db;
            
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.openDatabase: ${msg}`);
         }

     }
     async isConnection(dbName:string, readOnly: boolean): Promise&lt;boolean&gt; {
         try {
             const isConn = (await this.sqliteConnection.isConnection(dbName, readOnly)).result;
             if (isConn != undefined) {
                 return isConn
             } else {
                 throw new Error(`sqliteService.isConnection undefined`);
             }
            
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.isConnection: ${msg}`);
         }
     }
     async closeDatabase(dbName:string, readOnly: boolean):Promise&lt;void&gt; {
         try {
             const isConn = (await this.sqliteConnection.isConnection(dbName, readOnly)).result;
             if(isConn) {
                 await this.sqliteConnection.closeConnection(dbName, readOnly);
             }
             return;
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.closeDatabase: ${msg}`);
         }
     }
     async saveToStore(dbName: string): Promise&lt;void&gt; {
         try {
             await this.sqliteConnection.saveToStore(dbName);
             return;
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.saveToStore: ${msg}`);
         }
     }
     async saveToLocalDisk(dbName: string): Promise&lt;void&gt; {
         try {
             await this.sqliteConnection.saveToLocalDisk(dbName);
             return;
         } catch(err:any) {
             const msg = err.message ? err.message : err;
             throw new Error(`sqliteService.saveToLocalDisk: ${msg}`);
         }
     }
 }
 export default new SQLiteService();
</code></pre>
  </li>
  <li>
    <p>Open the <code>services/storage.service.ts</code> and replace the code with</p>

    <pre><code class="language-ts"> import {platform} from '../App';
 import { BehaviorSubject } from 'rxjs';
 import {ISQLiteService } from '../services/sqliteService'; 
 import {IDbVersionService } from '../services/dbVersionService';
 import { SQLiteDBConnection } from '@capacitor-community/sqlite';
 import { UserUpgradeStatements } from '../upgrades/user.upgrade.statements';
 import { User } from '../models/User';

 export interface IStorageService {
     initializeDatabase(): Promise&lt;void&gt;
     getUsers(): Promise&lt;User[]&gt;
     addUser(user: User): Promise&lt;number&gt;
     updateUserById(id: string, active: number): Promise&lt;void&gt; 
     deleteUserById(id: string): Promise&lt;void&gt;
     getDatabaseName(): string
     getDatabaseVersion(): number
 };
 class StorageService implements IStorageService  {
     versionUpgrades = UserUpgradeStatements;
     loadToVersion = UserUpgradeStatements[UserUpgradeStatements.length-1].toVersion;
     db!: SQLiteDBConnection;
     database: string = 'myuserdb';
     sqliteServ!: ISQLiteService;
     dbVerServ!: IDbVersionService;
     isInitCompleted = new BehaviorSubject(false);

     constructor(sqliteService: ISQLiteService, dbVersionService: IDbVersionService) {
         this.sqliteServ = sqliteService;
         this.dbVerServ = dbVersionService;
     }
        
     getDatabaseName(): string {
         return this.database;
     }
     getDatabaseVersion(): number {
         return this.loadToVersion;
     }
     async initializeDatabase(): Promise&lt;void&gt; {
         // create upgrade statements
         try {
             await this.sqliteServ.addUpgradeStatement({database: this.database,
                                                 upgrade: this.versionUpgrades});
             this.db = await this.sqliteServ.openDatabase(this.database, this.loadToVersion, false);
             const isData = await this.db.query("select * from sqlite_sequence");
             if(isData.values!.length === 0) {
             // create database initial users if any

             }

             this.dbVerServ.setDbVersion(this.database,this.loadToVersion);
             if( platform === 'web') {
             await this.sqliteServ.saveToStore(this.database);
             }
             this.isInitCompleted.next(true);
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`storageService.initializeDatabase: ${msg}`);
         }
     }
     async getUsers(): Promise&lt;User[]&gt;  {
         return (await this.db.query('SELECT * FROM users;')).values as User[];
     }
     async addUser(user: User): Promise&lt;number&gt; {
         const sql = `INSERT INTO users (name) VALUES (?);`;
         const res = await this.db.run(sql,[user.name]);
         if (res.changes !== undefined
             &amp;&amp; res.changes.lastId !== undefined &amp;&amp; res.changes.lastId &gt; 0) {
             return res.changes.lastId;
         } else {
             throw new Error(`storageService.addUser: lastId not returned`);
         }
     }
     async updateUserById(id: string, active: number): Promise&lt;void&gt; {
         const sql = `UPDATE users SET active=${active} WHERE id=${id}`;
         await this.db.run(sql);
     }
     async deleteUserById(id: string): Promise&lt;void&gt; {
         const sql = `DELETE FROM users WHERE id=${id}`;
         await this.db.run(sql);
     }

 }
 export default StorageService;
</code></pre>
  </li>
</ul>

<p>To manage the database versionning, a new service <code>DbnameVersionService</code> is required. In your file editor, go to <code>src/services</code> folder and create the <code>dbVersionService.ts</code> file</p>

<ul>
  <li>
    <p>Open the <code>services/dbVersionService.ts</code> file and replace the code with</p>

    <pre><code class="language-ts"> export interface IDbVersionService {
     setDbVersion(dbName: string, version: number): void
     getDbVersion(dbName: string):number| undefined
 };
 class DbVersionService implements IDbVersionService  {
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     setDbVersion(dbName: string, version: number) {
         this.dbNameVersionDict.set(dbName, version);
     };
     getDbVersion(dbName: string): number | undefined {
         const version =  this.dbNameVersionDict.get(dbName);
         return version;
     };
 }
 export default new DbVersionService();
</code></pre>
  </li>
</ul>

<h3 id="vue-plugin-implementation">Vue Plugin Implementation</h3>

<p>For Web applications, the plugin uses the Stencil component <code>jeep-sqlite</code> which implies some Vue files modification</p>

<ul>
  <li>
    <p>Open the <code>main.ts</code> file and replace the code with the following</p>

    <pre><code class="language-ts"> import { createApp } from 'vue'
 import App from './App.vue'
 import router from './router';

 import { IonicVue } from '@ionic/vue';

 /* Core CSS required for Ionic components to work properly */
 import '@ionic/vue/css/core.css';

 /* Basic CSS for apps built with Ionic */
 import '@ionic/vue/css/normalize.css';
 import '@ionic/vue/css/structure.css';
 import '@ionic/vue/css/typography.css';

 /* Optional CSS utils that can be commented out */
 import '@ionic/vue/css/padding.css';
 import '@ionic/vue/css/float-elements.css';
 import '@ionic/vue/css/text-alignment.css';
 import '@ionic/vue/css/text-transformation.css';
 import '@ionic/vue/css/flex-utils.css';
 import '@ionic/vue/css/display.css';

 /* Theme variables */
 import './theme/variables.css';

 import { Capacitor } from '@capacitor/core';
 import { JeepSqlite } from 'jeep-sqlite/dist/components/jeep-sqlite';
 import { defineCustomElements as pwaElements} from '@ionic/pwa-elements/loader';
 import SqliteService from './services/sqliteService'; 
 import DbVersionService from './services/dbVersionService';
 import StorageService from './services/storageService';
 import InitializeAppService from './services/initializeAppService';

 pwaElements(window);
 customElements.define('jeep-sqlite', JeepSqlite);
 const platform = Capacitor.getPlatform();

 const app = createApp(App)
 .use(IonicVue)
 .use(router);


 // Set the platform as global properties on the app
 app.config.globalProperties.$platform = platform;

 // Define and instantiate the required services
 const sqliteServ = new SqliteService();
 const dbVersionServ = new DbVersionService();
 const storageServ = new StorageService(sqliteServ, dbVersionServ);
 // Set the services as global properties on the app
 app.config.globalProperties.$sqliteServ = sqliteServ;
 app.config.globalProperties.$dbVersionServ = dbVersionServ;
 app.config.globalProperties.$storageServ = storageServ;

 //Define and instantiate the InitializeAppService
 const initAppServ = new InitializeAppService(sqliteServ, storageServ);
 
 const mountApp = () =&gt; {
     initAppServ.initializeApp()
     .then(() =&gt; {
         router.isReady().then(() =&gt; {
         app.mount('#app');
         });
     })
     .catch((error) =&gt; {
         console.error('App Initialization error:', error);
     });
 }

 if (platform !== "web") {
     mountApp();
 } else {
     window.addEventListener('DOMContentLoaded', async () =&gt; {
         const jeepEl = document.createElement("jeep-sqlite");
         document.body.appendChild(jeepEl);
         customElements.whenDefined('jeep-sqlite').then(() =&gt; {
             mountApp();
         })
         .catch ((err) =&gt; {
             console.error('jeep-sqlite creation error:', err);
         });
     });
 }
</code></pre>
    <p>As the goal is to ensure that the services (<code>SqliteService</code>, <code>DbVersionService</code> and <code>StorageService</code>) are unique and properly shared and available throughout the components, they have been set as global properties on the app.</p>
  </li>
  <li>
    <p>To initialize the application, an <code>InitializeAppService</code> service is execute prior mounting the app and has to be created.</p>
  </li>
  <li>
    <p>In your Editor add a new file <code>initializeAppService.ts</code> file under the folder <code>src/services</code>.</p>
  </li>
  <li>
    <p>In your editor, open the file <code>services/initializeAppService.ts</code> and replace the code with:</p>

    <pre><code class="language-ts"> import {ISQLiteService } from '../services/sqliteService'; 
 import {IStorageService } from '../services/storageService'; 

 export interface IInitializeAppService {
     initializeApp(): Promise&lt;boolean&gt;
 };

 class InitializeAppService implements IInitializeAppService  {
     appInit = false;
     sqliteServ!: ISQLiteService;
     storageServ!: IStorageService;
     platform!: string;

     constructor(sqliteService: ISQLiteService, storageService: IStorageService) {
         this.sqliteServ = sqliteService;
         this.storageServ = storageService;
         this.platform = this.sqliteServ.getPlatform();
     }
     async initializeApp() : Promise&lt;boolean&gt; {
         if(!this.appInit) {
             try {
                 if (this.platform === 'web') {
                     await this.sqliteServ.initWebStore();
                 }
                 // Initialize the myuserdb database
                 await this.storageServ.initializeDatabase();
                 if( this.platform === 'web') {
                     await this.sqliteServ.saveToStore(this.storageServ.getDatabaseName());
                 }
                 this.appInit = true;
             } catch(error: any) {
                 const msg = error.message ? error.message : error;
                 throw new Error(`initializeAppError.initializeApp: ${msg}`);
             }
         }
         return this.appInit;
     }
 }
 export default InitializeAppService;
</code></pre>
  </li>
  <li>
    <p>Open the <code>App.vue</code> file  and replace the code with</p>

    <pre><code class="language-ts"> &lt;template&gt;
 &lt;ion-app&gt;
     &lt;ion-router-outlet /&gt;
 &lt;/ion-app&gt;
 &lt;/template&gt;

 &lt;script setup lang="ts"&gt;
 import { IonApp, IonRouterOutlet } from '@ionic/vue';
 import AppMenu from '@/components/AppMenu.vue';
 &lt;/script&gt;
</code></pre>
  </li>
  <li>
    <p>Add a route <code>/users</code> in the <code>src/router/index.ts</code> file by adding</p>
  </li>
</ul>

<pre><code class="language-ts">  import { createRouter, createWebHistory } from '@ionic/vue-router';
    import { RouteRecordRaw } from 'vue-router';
    import HomePage from '../views/HomePage.vue';
    import UsersPage from '../views/UsersPage.vue';

    const routes: Array&lt;RouteRecordRaw&gt; = [
        {
            path: '/',
            redirect: '/home'
        },
        {
            path: '/home',
            name: 'Home',
            component: HomePage
        },
        {
            path: "/users",
            name: "Users",
            component: UsersPage,
        },
    ]

    const router = createRouter({
        history: createWebHistory(import.meta.env.BASE_URL),
        routes
    })

    export default router
</code></pre>

<h3 id="users-page-implementation">Users Page Implementation</h3>

<p>As you can see above, a route <code>/users</code> to a <code>UsersPage</code> has been added.
 Let’s create it.</p>

<ul>
  <li>
    <p>In your Editor, under <code>src/views</code> folder add a new page <code>UsersPage.vue</code>.</p>
  </li>
  <li>
    <p>Then open the <code>UsersPage.vue</code> file and add the following code:</p>

    <pre><code class="language-ts"> &lt;template&gt;
     &lt;ion-page&gt;
     &lt;ion-header&gt;
         &lt;ion-toolbar&gt;
         &lt;ion-title&gt;Managing Users&lt;/ion-title&gt;
         &lt;ion-buttons slot="start"&gt;
             &lt;ion-back-button text="home" default-href="/home"&gt;&lt;/ion-back-button&gt;
         &lt;/ion-buttons&gt;
         &lt;/ion-toolbar&gt;
     &lt;/ion-header&gt;
     &lt;ion-content&gt;
         &lt;div v-if="isInitComplete &amp;&amp; dbInitialized"&gt;
         &lt;ion-card&gt;
             &lt;h1&gt;Add New User&lt;/h1&gt;
             &lt;user-form :onAddUser="handleAddUser" /&gt;
         &lt;/ion-card&gt;
         &lt;ion-card&gt;
             &lt;h2&gt;Current Users&lt;/h2&gt;
             &lt;user-list :users="users" :onUpdateUser="handleUpdateUser" :onDeleteUser="handleDeleteUser" /&gt;
         &lt;/ion-card&gt;
         &lt;/div&gt;
     &lt;/ion-content&gt;
     &lt;/ion-page&gt;
 &lt;/template&gt;
 &lt;script lang="ts"&gt;
 import { defineComponent, ref, computed, getCurrentInstance, onMounted,
         onBeforeUnmount, watch, Ref } from 'vue';
 import { useIonRouter } from '@ionic/vue';
 import { IonPage, IonHeader, IonToolbar, IonButtons, IonBackButton, IonTitle,
         IonContent, IonCard} from '@ionic/vue';
 import { Toast } from '@capacitor/toast';
 import { User } from '@/models/User';
 import UserForm from '@/components/UserForm.vue';
 import UserList from '@/components/UserList.vue';
 import { useQuerySQLite } from '@/hooks/UseQuerySQLite';
 import { SQLiteDBConnection } from '@capacitor-community/sqlite';

 export default defineComponent({
     name: 'TestPage',
     components: { IonPage, IonHeader, IonToolbar, IonButtons,
      IonBackButton, IonTitle,
      IonContent, IonCard, UserForm, UserList },
     setup() {
         const dbNameRef = ref('');
         const isInitComplete = ref(false);
         const isDatabase = ref(false);
         const users = ref&lt;User[]&gt;([]);
         const db = ref(null);
         const appInstance = getCurrentInstance();

         const router = useIonRouter();
        
         const sqliteServ = appInstance?.appContext.config.globalProperties.$sqliteServ;
         const storageServ = appInstance?.appContext.config.globalProperties.$storageServ;

         const dbInitialized = computed(() =&gt; !!db.value);
         const platform = sqliteServ.getPlatform();

         const getAllUsers = async (db: Ref&lt;SQLiteDBConnection|null&gt;) =&gt; {
             const stmt = 'SELECT * FROM users';
             const values: any[] = [];
             const fetchData = await useQuerySQLite(db, stmt, values);
             users.value = fetchData;         
         }

         const openDatabase = async () =&gt; {
             try {
                 const dbUsersName = storageServ.getDatabaseName();
                 dbNameRef.value = dbUsersName;
                 const version = storageServ.getDatabaseVersion();
            
                 const database = await sqliteServ.openDatabase(dbUsersName, version, false);
                 db.value = database;
                 isDatabase.value = true;
             } catch (error) {
                 const msg = `Error open database: ${error}`;
                 console.error(msg);
                 Toast.show({
                     text: msg,
                     duration: 'long'
                 });
             }
         };
         const handleAddUser = async (newUser: User) =&gt; {
             if (db.value) {
                 const isConn = await sqliteServ.isConnection(dbNameRef.value, false);
                 const lastId = await storageServ.addUser(newUser);
                 newUser.id = lastId;
                 users.value.push(newUser as never);
             }
         };
         const handleUpdateUser = async (updUser: User) =&gt; {
             if (db.value) {
                 const isConn = await sqliteServ.isConnection(dbNameRef.value, false);
                 await storageServ.updateUserById(updUser.id.toString(), updUser.active);
                 users.value = users.value.map((user: User) =&gt; {
                     if (user.id === updUser.id) {
                     // Clone the user and update the active property
                     return { ...user, active: updUser.active };
                     } else {
                     return user;
                     }
                 });
             }
         };
  
         const handleDeleteUser = async (userId: number) =&gt; {
             if (db.value) {
                 const isConn = await sqliteServ.isConnection(dbNameRef.value, false);
                 await storageServ.deleteUserById(userId.toString());
                 users.value = users.value.filter(user =&gt; (user as User).id !== userId);
             }
         };
         onMounted(() =&gt; {
             const initSubscription = storageServ.isInitCompleted.subscribe(async (value: boolean) =&gt; {
                 isInitComplete.value = value;
                 if (isInitComplete.value === true) {
                     const dbUsersName = storageServ.getDatabaseName();
                     if (platform === "web") {
                     customElements.whenDefined('jeep-sqlite').then(async () =&gt; {
                         await openDatabase();
                     }).catch((error) =&gt; {
                         const msg = `Error open database: ${error}`;
                         console.log(msg);
                         Toast.show({
                         text: msg,
                         duration: 'long'
                         });
                     });
                     } else {
                     await openDatabase();
                     }
                 }
             });
         });
         onBeforeUnmount(() =&gt; {
             sqliteServ.closeDatabase(dbNameRef.value, false)
             .then(() =&gt; {
                 isDatabase.value = false;
             }).catch((error: any) =&gt; {
                 const msg = `Error close database:
                             ${error.message ? error.message : error}`;
                 console.error(msg);
                 Toast.show({
                 text: msg,
                 duration: 'long'
                 });
             });
         });

         watch(isDatabase, (newIsDatabase) =&gt; {
             if (newIsDatabase) {
             getAllUsers(db).then(() =&gt; {

             })
             .catch((error: any) =&gt; {
                 const msg = `close database:
                             ${error.message ? error.message : error}`;
                 console.error(msg);
                 Toast.show({
                 text: msg,
                 duration: 'long'
                 });
             });         
             } else {
                 const msg = `newDb is null`;
                 console.error(msg);
                 Toast.show({
                     text: msg,
                     duration: 'long'
                     });
             }
         });

         return {isInitComplete, dbInitialized, users, handleAddUser,
                  handleUpdateUser, handleDeleteUser}
         },
     });
 &lt;/script&gt;
</code></pre>
  </li>
</ul>

<h3 id="users-component-implementation">Users Component Implementation</h3>

<p>In that tutorial we use a simple UI interface for CRUD operations through the use of a <code>UserForm</code> and a <code>UserList</code> Vue component.</p>

<ul>
  <li>
    <p>Under <code>src/components</code> folder create two new files <code>UserForm.vue</code> and <code>UserList.vue</code>.</p>
  </li>
  <li>
    <p>Open the <code>components/UserForm.vue</code> file and copy the following code</p>

    <pre><code class="language-ts"> &lt;template&gt;
     &lt;div class="UserForm"&gt;
     &lt;ion-input
         ref="ionNameEl"
         :value="nameModel"
         @ionInput="handleNameInput($event)"
         type="text"
         placeholder="Rose Miller"
     &gt;&lt;/ion-input&gt;
     &lt;!-- version 2
     &lt;ion-input
         ref="ionEmailEl"
         :value="emailModel"
         @ionInput="handleEmailInput($event)"
         type="email"
         placeholder="Email"
     &gt;&lt;/ion-input&gt;
     --&gt;
     &lt;ion-button expand="full" @click="handleSubmit" :disabled="!isFormValid"&gt;
         Add User
     &lt;/ion-button&gt;
     &lt;/div&gt;
 &lt;/template&gt;
  
 &lt;script lang="ts"&gt;
 import { ref } from 'vue';
 import { defineComponent, watch } from 'vue';
 import { IonInput, IonButton } from '@ionic/vue';
    
 export default defineComponent({
     name: 'UserForm',
     props: {
     onAddUser: Function,
     },
     components: {IonInput, IonButton},
     setup(props) {
         const ionNameEl = ref();
         const nameModel = ref('');
         const ionEmailEl = ref();
         const emailModel = ref('');
         const isFormValid = ref(false);
    
         const handleNameInput = (ev: { target: any; }) =&gt; {
             const value = ev.target!.value;
             const fileterdValue = value.replace(/[^a-zA-Z0-9-' ']+/g, '');
             nameModel.value = value;
        
             const inputCmp = ionNameEl.value;
             if (inputCmp !== undefined) {
                 inputCmp.$el.value  = fileterdValue;
             }
         };
         /* Version 2
         const handleEmailInput = (ev:  { target: any; }) =&gt; {
             const value = ev.target!.value;

             // Update both the state variable and
             // the component to keep them in sync.

             emailModel.value = value;

             const inputCmp = ionEmailEl.value;
             if (inputCmp !== null) {
                 inputCmp.$el.value = value;
             }

         };
         */    
         const handleSubmit = () =&gt; {
             if (nameModel.value /*&amp;&amp; emailModel.value */) {
                 const newUser = {
                     id: Date.now(), // do not care about the id value (generated by sqlite)
                     name: nameModel.value,
                     active: 1,
                     /* email: emailModel.value, // version 2 */
                 };
                 if (typeof props.onAddUser === 'function') {
                     props.onAddUser(newUser);
                 }
            
                 nameModel.value = '';
                 /* emailModel.value = ''; // version 2 */
                 isFormValid.value = false;
             }
         };
  
         const hasTwoWords = (input: string) =&gt; {
             const words = input.trim().split(' ');
             return words.length === 2 &amp;&amp; words.every((word) =&gt; word !== '');
         };

         /* Version 2
         const isValidEmail = (email) =&gt; {
             if (email.length === 0) {
                 return false;
             }
             const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,}$/;
             return emailRegex.test(email);
         };
         */
         // Watch 'name' and 'email' for changes and update 'isFormValid'
         watch([nameModel/*, emailModel*/], ([newName/*, newEmail*/]) =&gt; {
             isFormValid.value = hasTwoWords(newName) /* &amp;&amp; isValidEmail(newEmail)*/;
         });  
  
         return {
             ionNameEl,
             nameModel,
             /* emailModel, */
             isFormValid,
             handleNameInput,
             /*handleEmailInput,*/
             handleSubmit,
         };
     },
 });
 &lt;/script&gt;
</code></pre>
  </li>
  <li>
    <p>Open the <code>components/UserList.vue</code> file and copy the following code</p>

    <pre><code class="language-ts"> &lt;template&gt;
     &lt;ion-list class="UserList"&gt;
     &lt;ion-item v-for="user in users" :key="user.id"&gt;
         &lt;ion-checkbox
         ref="ionActiveEl"
         slot="start"
         :checked="user.active==1 ? true: false"
         :activeModel="user.active"
         @ionChange="handleCheckboxChange(user)"
         &gt;&lt;/ion-checkbox&gt;
          - 
         &lt;ion-button
         slot="end"
         fill="clear"
         color="danger"
         @click="handleDeleteUser(user.id)"
         &gt;
         &lt;ion-icon :icon="trash" /&gt;
         &lt;/ion-button&gt;
     &lt;/ion-item&gt;
     &lt;/ion-list&gt;
 &lt;/template&gt;
  
 &lt;script lang="ts"&gt;
 import { defineComponent, ref } from 'vue';
 import { IonList, IonItem, IonCheckbox, IonButton, IonIcon, IonLabel } from '@ionic/vue';
 import { User } from '@/models/User';
 import { trash } from 'ionicons/icons';
  
  
 export default defineComponent({
     name: 'UserList',
     props: {
         users: Array as () =&gt; User[],
         onUpdateUser: Function,
         onDeleteUser: Function
     },
     components: { IonList, IonItem, IonCheckbox, IonButton, IonIcon, IonLabel },
     setup(props) {
         const ionActiveEl = ref();
         const handleCheckboxChange = (user: User) =&gt; {
             // Create a new user object with the updated active value
             const updatedUser = { ...user, active: user.active === 1 ? 0 : 1 };
             if (typeof props.onUpdateUser === 'function') {
                 props.onUpdateUser(updatedUser);
             }
         };
         const handleDeleteUser = (userId: number) =&gt; {
             if (typeof props.onDeleteUser === 'function') {
                 props.onDeleteUser(userId);
             }
         }
         return {
             handleCheckboxChange, handleDeleteUser, trash
         };
     },
 });
 &lt;/script&gt;
</code></pre>

    <p>!!! Caution Between the &lt;/ion-checkbox&gt; &lt;ion-button tags
 You must read <code>Double left Curly Bracket</code> user.id <code>Double Right Curly Bracket</code> - <code>Double left Curly Bracket</code> user.name <code>Double Right Curly Bracket</code></p>
  </li>
</ul>

<h3 id="modify-the-home-page">Modify the Home Page</h3>

<p>The <code>Home</code> page will be modify to include:</p>

<pre><code>- a company logo
- a welcome text
- a menu to access application pages
</code></pre>

<p>This will be achieved by creating new Vue components that will be integrated in the <code>Home</code> page and for the menu component in the <code>App.tx</code> file</p>

<ul>
  <li>
    <p>Create an <code>AppLogo</code> Vue component</p>

    <ul>
      <li>
        <p>In your Editor create a <code>AppLogo.vue</code> file under <code>src/components</code>folder and copy the following code</p>

        <pre><code class="language-ts">  &lt;template&gt;
      &lt;div class="AppLogo"&gt;
      &lt;img src="/assets/JeepQLogo.png" alt="App Logo" width="128" height="128" /&gt;
      &lt;/div&gt;
  &lt;/template&gt;
        
  &lt;script lang="ts"&gt;
  import { defineComponent } from 'vue';
  export default defineComponent({
  name: 'AppLogo',
  });
  &lt;/script&gt;

  &lt;style scoped&gt;
  .AppLogo {
      width: 100%;
      max-height: 200px;
      display: flex;
      justify-content: center;
  }
  &lt;/style&gt;
</code></pre>
      </li>
    </ul>

    <p>Obviously use your own logo and store it in the <code>public/assets</code> folder.</p>
  </li>
  <li>
    <p>Create an <code>AppIntroText</code> Vue component</p>

    <ul>
      <li>
        <p>In your Editor create a <code>AppIntroText.vue</code> file under <code>src/components</code>folder and copy the following code</p>

        <pre><code class="language-ts">  &lt;template&gt;
      &lt;div class="AppIntroText"&gt;
          &lt;h3&gt;
          Welcome to the Ionic7/Vue SQLite Database CRUD App Example Tutorial
          &lt;/h3&gt;
          &lt;h4&gt;using @capacitor-community/sqlite&lt;/h4&gt;
      &lt;/div&gt;
  &lt;/template&gt;
  &lt;script lang="ts"&gt;
  import { defineComponent } from 'vue';
  export default defineComponent({
  name: 'AppIntroText',
  });
  &lt;/script&gt;
  &lt;style scoped&gt;
  .AppIntroText {
      width: 100%;
      max-height: 200px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      text-align: center;
      margin-top: 5%;
  }
  &lt;/style&gt;
</code></pre>
      </li>
    </ul>

    <p>Fill free to put whatever text you would like to see</p>
  </li>
  <li>
    <p>Create an <code>AppMenuButton</code> Vue component</p>

    <ul>
      <li>
        <p>In your Editor create a <code>AppMenuButton.vue</code> file under <code>src/components</code>folder and copy the following code</p>

        <pre><code class="language-ts">  &lt;template&gt;
  &lt;IonMenuButton slot="end" /&gt;
  &lt;/template&gt;
        
  &lt;script lang="ts"&gt;
  import { defineComponent } from 'vue';
  import { IonMenuButton} from '@ionic/vue';
  export default defineComponent({
  name: 'AppMenuButton',
  components: {IonMenuButton}
  });
  &lt;/script&gt;
</code></pre>
      </li>
    </ul>
  </li>
  <li>
    <p>Then the <code>views/HomePage.vue</code> file can be modified as below to include all these components:</p>

    <pre><code class="language-ts"> &lt;template&gt;
 &lt;ion-page&gt;
     &lt;ion-header :translucent="true"&gt;
     &lt;ion-toolbar&gt;
         &lt;app-menu-button&gt;&lt;/app-menu-button&gt;
         &lt;ion-title&gt;Home&lt;/ion-title&gt;
     &lt;/ion-toolbar&gt;
     &lt;/ion-header&gt;
     &lt;ion-content :fullscreen="true"&gt;
     &lt;ion-header collapse="condense"&gt;
         &lt;ion-toolbar&gt;
         &lt;ion-title size="large"&gt;Home&lt;/ion-title&gt;
         &lt;/ion-toolbar&gt;
     &lt;/ion-header&gt;
     &lt;div id="container"&gt;
         &lt;app-logo&gt;&lt;/app-logo&gt;
         &lt;app-intro-text&gt;&lt;/app-intro-text&gt;
     &lt;/div&gt;
     &lt;/ion-content&gt;
 &lt;/ion-page&gt;
 &lt;/template&gt;

 &lt;script lang="ts"&gt;
 import { defineComponent } from 'vue';
 import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/vue';
 import AppLogo from '@/components/AppLogo.vue'
 import AppIntroText from '@/components/AppIntroText.vue'
 import AppMenuButton from '@/components/AppMenuButton.vue'

 export default defineComponent({
     name: 'HomePage',
     components: { IonPage, IonHeader, IonToolbar, IonTitle,
         IonContent, AppLogo, AppIntroText, AppMenuButton },
     setup () {

     } 
 });
 &lt;/script&gt;

 &lt;style scoped&gt;
 #container {
     text-align: center;  
     position: relative;
     top: 10%;
     left: 0;
     right: 0;
     display: flex;
     flex-direction: column;
 }
 &lt;/style&gt;
</code></pre>
  </li>
</ul>

<h3 id="add-a-menu-to-the-app">Add a Menu to the App</h3>

<ul>
  <li>
    <p>For easy maintenance, the menu is implemented as a Vue component.</p>

    <ul>
      <li>In your Editor create a <code>AppMenu.vue</code> file under <code>src/components</code>folder and copy the following code</li>
    </ul>

    <pre><code class="language-ts"> &lt;template&gt;
     &lt;ion-menu class="AppMenu" side="end" content-id="main-content"&gt;
     &lt;ion-header&gt;
         &lt;ion-toolbar&gt;
         &lt;ion-title&gt;Menu Content&lt;/ion-title&gt;
         &lt;/ion-toolbar&gt;
     &lt;/ion-header&gt;
     &lt;ion-content&gt;
         &lt;ion-list&gt;
         &lt;ion-item @click="closeMenu"&gt;
             &lt;ion-button size="default" router-link="/users" expand="full"&gt;Managing Users&lt;/ion-button&gt;
         &lt;/ion-item&gt;
         &lt;!-- ... other menu items --&gt;
         &lt;/ion-list&gt;
     &lt;/ion-content&gt;
     &lt;/ion-menu&gt;
 &lt;/template&gt;
  
 &lt;script lang="ts"&gt;
 import { IonMenu, IonHeader, IonToolbar, IonTitle, IonContent, IonList,
         IonItem, IonButton } from '@ionic/vue';
 import { defineComponent } from 'vue';
 import { useIonRouter } from '@ionic/vue';

 export default defineComponent({
     name: 'AppMenu',
     components: { IonMenu, IonHeader, IonToolbar, IonTitle, IonContent,
                 IonList, IonItem, IonButton },
     setup() {
         const router = useIonRouter();
    
         const closeMenu = () =&gt; {
             const menu = document.querySelector('ion-menu');
             menu!.close();
         };
         return {closeMenu, router}
     },
 });
 &lt;/script&gt;
 &lt;style scoped&gt;
     .AppMenu  ion-button {
         --background: transparent;
         --color: initial;
         font-size: 18px;
     }
 &lt;/style&gt;
</code></pre>
  </li>
  <li>
    <p>Then modify the <code>App.vue</code> file</p>
    <ul>
      <li>
        <p>by adding</p>

        <pre><code class="language-ts">  import AppMenu from './components/AppMenu/AppMenu';
</code></pre>
      </li>
      <li>
        <p>replace <code>&lt;ion-router-outlet /&gt;</code> with</p>

        <pre><code class="language-html">  &lt;app-menu /&gt;
  &lt;ion-router-outlet id="main-content"/&gt;
</code></pre>
      </li>
    </ul>
  </li>
</ul>

<h3 id="update-config-and-packagejson-scripts">Update Config and Package.json Scripts</h3>

<ul>
  <li>
    <p>For Web application only the appID of the <code>capacitor.config.ts</code> must be amended with <code>YOUR_APP_ID</code></p>
  </li>
  <li>For the <code>package .json</code> file
    <ul>
      <li>
        <p>add the following script below <code>"build": "tsc &amp;&amp; vite build",</code>,</p>

        <pre><code class="language-json">  "build:web": "npm run copy:sql:wasm &amp;&amp; vue-tsc &amp;&amp; vite build",
  "ionic:serve:before": "npm run copy:sql:wasm",
  "copy:sql:wasm": "copyfiles -u 3 node_modules/sql.js/dist/sql-wasm.wasm public/assets",
</code></pre>
      </li>
      <li>
        <p>modify the <code>"dev": "vite",</code> with</p>

        <pre><code class="language-json">  "dev": "npm run copy:sql:wasm &amp;&amp; vite",
</code></pre>
      </li>
    </ul>
  </li>
  <li>
    <p>For the <code>vite.config.ts</code>file to reduce the size of the chunks after minification add the following lines after the <code>plugins</code> block</p>

    <pre><code class="language-ts"> build: {
     rollupOptions: {
         output:{
             manualChunks(id) {
                 if (id.includes('node_modules')) {
                     return id.toString().split('node_modules/')[1].split('/')[0].toString();
                 }
             }
         }
     }
 },
</code></pre>
  </li>
</ul>

<h3 id="run-the-web-sqlite-app">Run the Web SQLite App</h3>

<ul>
  <li>
    <p>To run the Web app use the below command</p>

    <pre><code class="language-bash"> npm run dev
</code></pre>
  </li>
  <li>
    <p>In your favorite Browser enter</p>

    <pre><code> http://localhost:5173/
</code></pre>
  </li>
  <li>
    <p>This will bring you to the <code>Home</code> page</p>

    <div align="center"><br /><img src="/images/Ionic7-Vue-SQLite-HomePage.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p>To open the menu, click on the <span style="font-size: 24px;"><ion-icon name="menu"></ion-icon></span> icon in the top left corner.</p>

    <div align="center"><br /><img src="/images/Ionic7-Vue-SQLite-MenuOpen.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p> In the <strong><code>Menu Content</code></strong> click on <strong><code>MANAGING USERS</code></strong></p>

    <div align="center"><br /><img src="/images/Ionic7-Vue-SQLite-Managing-Users.png" width="250" /></div>
    <p><br /></p>
  </li>
</ul>

<p>On the screen-copy, ones has entered already some users.</p>
<ul>
  <li>To input new users
    <ul>
      <li>type a new user on the input field “Rose Miller”  under Name</li>
      <li>press on the <code>"Add User"</code> button will add the user.</li>
    </ul>
  </li>
  <li>
    <p>To update the <code>active</code>value for a user, press on the check icon on the left it will toggle the value from 1 to 0 or from 0 to 1.</p>
  </li>
  <li>
    <p>To delete a user press on the <code>trash</code> icon.</p>
  </li>
  <li>To save the database to store leave the <code>UsersPage</code> by going back <code>Home</code>.</li>
</ul>

<p>The database location can be see in the application tab of the development tools.</p>

<div align="center"><br /><img src="/images/Ionic7-Vue-SQLite-Database-Location.png" width="80%" /></div>
<p><br /></p>

<h3 id="part-1-conclusion">Part 1 Conclusion</h3>

<p>We have completed the Part 1 - Web application of the Ionic 7 SQLite Database CRUD App Example Tutorial using Vue and @capacitor-community/sqlite.</p>

<p>We learned how to implement the ‘@capacitor-community/sqlite’ plugin in the Vue Framework using standalone components on a Web platform.</p>

<p>We learned to use <code>app.config.globalProperties</code> to ensure that the services are available to all components within the app.</p>

<p>We learned how to create an application menu.</p>

<p>We learned how to used some basic methods of the ‘@capacitor-community/sqlite’ plugin to create a CRUD application from scratched and store persistent SQLite data into the Web IndexedDB browser database.</p>

<p>Enjoy your development from there.</p>

<h2 id="part-2---native---table-of-contents">Part 2 - Native - Table of Contents</h2>

<hr />
<ul>
  <li><a href="#install-native-required-packages">Install Native Required Packages</a></li>
  <li><a href="#update-config-file">Update Config file</a></li>
  <li><a href="#update-packagejson-scripts">Update Package.json Scripts</a></li>
  <li><a href="#run-the-ios-app">Run the iOS App</a></li>
  <li><a href="#run-the-android-app">Run the Android App</a></li>
  <li><a href="#run-the-electron-app">Run the Electron App</a></li>
  <li><a href="#part-1-conclusion">Part 2 Conclusion</a></li>
</ul>

<hr />

<h3 id="install-native-required-packages">Install Native Required Packages</h3>

<ul>
  <li>
    <p>In order to build Android, iOS, or Electron applications on specific devices, it is necessary to install the necessary capacitor packages first. So run the following commands:</p>

    <pre><code class="language-bash"> npm install --save @capacitor/android
 npm install --save @capacitor/ios
 npm install --save @capacitor-community/electron
</code></pre>
  </li>
  <li>
    <p>Integrate the various platforms into the application.</p>

    <pre><code class="language-bash"> npm run build
 npx cap add android
 npx cap add ios
 npx cap add @capacitor-community/electron
</code></pre>
  </li>
</ul>

<h3 id="update-config-file">Update Config file</h3>

<p>The <code>capacitor.config.ts</code> file specifies parameters that the plugin needs, such as database location, database encryption, and the use of biometric authentication for access security. Such settings may be platform specific.</p>

<ul>
  <li>
    <p>Please modify the <code>capacitor.config.ts</code> file as below :</p>

    <pre><code class="language-ts"> import { CapacitorConfig } from '@capacitor/cli';

 const config: CapacitorConfig = {
 appId: 'YOUR_APP_ID',
 appName: 'YOUR_APP_NAME',
 webDir: 'dist',
 loggingBehavior: 'debug',
 server: {
     androidScheme: "http"
 },
 plugins: {
     CapacitorSQLite: {
     iosDatabaseLocation: 'Library/CapacitorDatabase',
     iosIsEncryption: false,
     iosKeychainPrefix: 'YOUR_APP_NAME',
     iosBiometric: {
         biometricAuth: false,
         biometricTitle : "Biometric login for capacitor sqlite"
     },
     androidIsEncryption: false,
     androidBiometric: {
         biometricAuth : false,
         biometricTitle : "Biometric login for capacitor sqlite",
         biometricSubTitle : "Log in using your biometric"
     },
     electronIsEncryption: false,
     electronWindowsLocation: "C:\\ProgramData\\CapacitorDatabases",
     electronMacLocation: "/Users/YOUR_NAME/CapacitorDatabases",
     electronLinuxLocation: "Databases"
     }
 }
 };
 export default config;
</code></pre>
  </li>
</ul>

<h3 id="update-packagejson-scripts">Update Package.json Scripts</h3>

<ul>
  <li>
    <p>First install a new package to remove the sql.js wasm file to reduce the native package size</p>

    <pre><code class="language-bash"> npm install --save-dev rimraf
</code></pre>
  </li>
  <li>
    <p>Open the <code>package.json</code> file and replace the scripts section with:</p>

    <pre><code class="language-json"> "scripts": {
     "dev": "npm run copy:sql:wasm &amp;&amp; vite",
     "build:web": "npm run copy:sql:wasm &amp;&amp; npm run build",
     "build:native": "npm run remove:sql:wasm &amp;&amp; npm run build",
     "build": "vue-tsc &amp;&amp; vite build",
     "preview": "vite preview",
     "ionic:serve:before": "npm run copy:sql:wasm",
     "copy:sql:wasm": "copyfiles -u 3 node_modules/sql.js/dist/sql-wasm.wasm public/assets",
     "remove:sql:wasm": "rimraf public/assets/sql-wasm.wasm",
     "ios:start": "npm run remove:sql:wasm &amp;&amp; npm run build:native &amp;&amp; npx cap sync &amp;&amp; npx cap copy &amp;&amp; npx cap open ios",
     "android:start": "npm run remove:sql:wasm &amp;&amp; npm run build:native &amp;&amp; npx cap sync &amp;&amp; npx cap copy &amp;&amp; npx cap open android",
     "electron:install": "cd electron &amp;&amp; npm install &amp;&amp; cd ..",
     "electron:prepare": "npm run remove:sql:wasm &amp;&amp; npm run build &amp;&amp; npx cap sync @capacitor-community/electron &amp;&amp; npx cap copy @capacitor-community/electron",
     "electron:start": "npm run electron:prepare &amp;&amp; cd electron &amp;&amp; npm run electron:start",
     "clean:vite:cache": "vite clean",
     "test:e2e": "cypress run",
     "test:unit": "vitest",
     "lint": "eslint"
 },
</code></pre>
  </li>
</ul>

<h3 id="run-the-ios-app">Run the iOS App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> npm run ios:start
</code></pre>
  </li>
  <li>
    <p>In Xcode wait for indexed file to complete, clean the project and run the app. You will get the following screen for the Home Page</p>

    <div align="center"><br /><img src="/images/Part2-iOS-Ionic7-Vue-SQLite-HomePage.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p>To open the menu, click on the <span style="font-size: 24px;"><ion-icon name="menu"></ion-icon></span> icon in the top left corner.</p>

    <div align="center"><br /><img src="/images/Part2-iOS-Ionic7-Vue-SQLite-MenuOpen.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p> In the <strong><code>Menu Content</code></strong> click on <strong><code>MANAGING USERS</code></strong></p>

    <div id="banner" style="overflow: hidden; display: flex; justify-content:space-around;">
 <div style="max-width: 40%;"><img src="/images/Part2-iOS-Ionic7-Vue-SQLite-Managing-Users-1.png" /></div>
 <div style="max-width: 38.1035%;"><img src="/images/Part2-iOS-Ionic7-Vue-SQLite-Managing-Users-2.png" /></div>
</div>
  </li>
</ul>

<p>On the screen-copies, ones has entered already some users.</p>
<ul>
  <li>To input new users
    <ul>
      <li>type a new user on the input field “Rose Miller”  under Name</li>
      <li>press on the <code>"Add User"</code> button will add the user.</li>
    </ul>
  </li>
  <li>
    <p>To update the <code>active</code>value for a user, press on the check icon on the left it will toggle the value from 1 to 0 or from 0 to 1.</p>
  </li>
  <li>
    <p>To delete a user press on the <code>trash</code> icon.</p>
  </li>
  <li>To leave the <code>UsersPage</code> by going back <code>Home</code>.</li>
</ul>

<h3 id="run-the-android-app">Run the Android App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> npm run android:start
</code></pre>
  </li>
  <li>
    <p>In Android Studio</p>

    <ul>
      <li>go to the menu Android/Preferences/Build, Execution, Deployment/Build Tools/Gradle and then select the gradle JDK <code>17 Oracle OpenJDK Version 17.0.7</code>. Then press <code>Apply</code> and <code>OK</code>.</li>
      <li>go to File/Sync Project With Gradle Files.</li>
      <li>go to Build/Clean Project.</li>
      <li>select your Emulator or Physical Device.</li>
      <li>run the app</li>
    </ul>
  </li>
  <li>
    <p>Screenshot of the screen for the Home page:</p>
  </li>
</ul>

<div align="center"><br /><img src="/images/Part2-Android-Ionic7-Vue-SQLite-HomePage.png" width="50%" /></div>
<p><br /></p>

<ul>
  <li>
    <p>To open the menu, click on the <span style="font-size: 24px;"><ion-icon name="menu"></ion-icon></span> icon in the top left corner.</p>

    <div align="center"><br /><img src="/images/Part2-Android-Ionic7-Vue-SQLite-MenuOpen.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p> In the <strong><code>Menu Content</code></strong> click on <strong><code>MANAGING USERS</code></strong></p>

    <div id="banner" style="overflow: hidden; display: flex; justify-content:space-around;">
 <div style="max-width: 40%;"><img src="/images/Part2-Android-Ionic7-Vue-SQLite-Managing-Users-1.png" /></div>
 <div style="max-width: 39.81%;"><img src="/images/Part2-Android-Ionic7-Vue-SQLite-Managing-Users-2.png" /></div>
</div>
  </li>
</ul>

<p>On the screen-copies, ones has entered already some users.</p>
<ul>
  <li>To input new users
    <ul>
      <li>type a new user on the input field “Rose Miller”  under Name</li>
      <li>press on the <code>"Add User"</code> button will add the user.</li>
    </ul>
  </li>
  <li>
    <p>To update the <code>active</code>value for a user, press on the check icon on the left it will toggle the value from 1 to 0 or from 0 to 1.</p>
  </li>
  <li>
    <p>To delete a user press on the <code>trash</code> icon.</p>
  </li>
  <li>To leave the <code>UsersPage</code> by going back <code>Home</code>.</li>
</ul>

<h3 id="run-the-electron-app">Run the Electron App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> cd electron
</code></pre>
  </li>
  <li>
    <p>Open the <code>package.json</code> file and replace the scripts:, dependencies:, devDependencies: sections with:</p>

    <pre><code class="language-json"> "scripts": {
     "build": "tsc &amp;&amp; electron-rebuild",
     "electron:start-live": "node ./live-runner.js",
     "electron:start": "npm run build &amp;&amp;  electron --inspect=5858 ./",
     "electron:pack": "npm run build &amp;&amp; electron-builder build --dir -c ./electron-builder.config.json",
     "electron:make": "npm run build &amp;&amp; electron-builder build -c ./electron-builder.config.json -p always"
 },
 "dependencies": {
     "@capacitor-community/electron": "^4.1.2",
     "@capacitor-community/sqlite": "5.2.3",
     "better-sqlite3-multiple-ciphers": "^8.4.0",
     "chokidar": "~3.5.3",
     "crypto": "^1.0.1",
     "crypto-js": "^4.1.1",
     "electron-is-dev": "~2.0.0",
     "electron-json-storage": "^4.6.0",
     "electron-serve": "~1.1.0",
     "electron-unhandled": "~4.0.1",
     "electron-updater": "~5.0.1",
     "electron-window-state": "~5.0.3",
     "jszip": "^3.10.1",
     "node-fetch": "2.6.7"
 },
 "devDependencies": {
     "@electron/rebuild": "^3.3.0",
     "@types/better-sqlite3": "^7.6.4",
     "@types/crypto-js": "^4.1.1",
     "@types/electron-json-storage": "^4.5.0",
     "electron": "^25.2.0",
     "electron-builder": "^24.6.3",
     "typescript": "~4.3.5"
 },

</code></pre>
  </li>
  <li>
    <p>In your Editor delete the <code>node_modules</code> folder and <code>package-lock.json</code> file.</p>
  </li>
  <li>
    <p>Then run the following commands:</p>

    <pre><code class="language-bash"> npm install
 cd ..
 npm run electron:start
</code></pre>
  </li>
  <li>
    <p>Screenshot of the screen for the Home page:</p>
  </li>
</ul>

<div align="center"><br /><img src="/images/Part2-Electron-Ionic7-Vue-SQLite-HomePage.png" width="50%" /></div>
<p><br /></p>

<ul>
  <li>
    <p>To open the menu, click on the <span style="font-size: 24px;"><ion-icon name="menu"></ion-icon></span> icon in the top left corner.</p>

    <div align="center"><br /><img src="/images/Part2-Electron-Ionic7-Vue-SQLite-MenuOpen.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p> In the <strong><code>Menu Content</code></strong> click on <strong><code>MANAGING USERS</code></strong></p>

    <div id="banner" style="overflow: hidden; display: flex; justify-content:space-around;">
 <div style="max-width: 40%;"><img src="/images/Part2-Electron-Ionic7-Vue-SQLite-Managing-Users-1.png" /></div>
 <div style="max-width: 39.84%;"><img src="/images/Part2-Electron-Ionic7-Vue-SQLite-Managing-Users-2.png" /></div>
</div>
  </li>
</ul>

<p>On the screen-copies, ones has entered already some users.</p>
<ul>
  <li>To input new users
    <ul>
      <li>type a new user on the input field “Rose Miller”  under Name</li>
      <li>press on the <code>"Add User"</code> button will add the user.</li>
    </ul>
  </li>
  <li>
    <p>To update the <code>active</code>value for a user, press on the check icon on the left it will toggle the value from 1 to 0 or from 0 to 1.</p>
  </li>
  <li>
    <p>To delete a user press on the <code>trash</code> icon.</p>
  </li>
  <li>To leave the <code>UsersPage</code> by going back <code>Home</code>.</li>
</ul>

<h3 id="part-2-conclusion">Part 2 Conclusion</h3>

<p>We have completed the Part 2 - Native and Electron applications of the Ionic 7 SQLite Database CRUD App Example Tutorial using Vue framework and @capacitor-community/sqlite.</p>

<p>We have learned to adapt the <code>capacitor.config.ts</code>file and the modify the scripts: section of the <code>package.json</code>file for native apps</p>

<p>We learned how to build and run the application for each native platforms.</p>

<p>Enjoy your development from there.</p>]]></content><author><name>Quéau Jean Pierre</name></author><category term="Other" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Ionic 7 SQLite Database CRUD App Example Tutorial using React and @capacitor-community/sqlite</title><link href="https://jepiqueau.github.io/2023/08/31/Ionic7React-SQLite-CRUD-App.html" rel="alternate" type="text/html" title="Ionic 7 SQLite Database CRUD App Example Tutorial using React and @capacitor-community/sqlite" /><published>2023-08-31T00:00:00+00:00</published><updated>2023-08-31T00:00:00+00:00</updated><id>https://jepiqueau.github.io/2023/08/31/Ionic7React-SQLite-CRUD-App</id><content type="html" xml:base="https://jepiqueau.github.io/2023/08/31/Ionic7React-SQLite-CRUD-App.html"><![CDATA[<hr />

<p><em>last updated on November 6, 2023 by Quéau Jean Pierre</em></p>

<p>In that tutorial we will learned how to create a Ionic7/React basic CRUD application and implement the @capacitor-community/sqlite plugin to store the data in a SQLite database.</p>

<p>The first part of the tutorial will concentrate on how to create that application and run it on a Web browser where the data will be stored on an Indexed database using sql.js and localForage modules.
Go to <a href="#part-1---web---table-of-contents">Part 1 - Web - Table of Contents</a></p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/SQLite/main/Part-1/ionic7-react-sqlite-app">Part-1/ionic7-react-sqlite-app</a></p>

<p>Thanks to the Ionic Team and their hard work to bring CAPACITOR 5, the second part will concentrate on native platforms (iOS and Android) and also on Electron platform.
Go to <a href="#part-2---native---table-of-contents">Part 2 - Native - Table of Contents</a></p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/SQLite/Part-2/ionic7-react-sqlite-app">Part-2/ionic7-react-sqlite-app</a></p>

<h2 id="part-1---web---table-of-contents">Part 1 - Web - Table of Contents</h2>

<hr />
<ul>
  <li><a href="#install-new-ionic-application">Install New Ionic Application</a></li>
  <li><a href="#install-required-packages">Install Required Packages</a></li>
  <li><a href="#create-a-react-cli-config-file">Create a React Cli Config file</a></li>
  <li><a href="#create-the-sqlite-database">Create the SQLite Database</a></li>
  <li><a href="#create-crud-and-sqlite-services">Create CRUD and SQLite Services</a></li>
  <li><a href="#react-plugin-implementation">React Plugin Implementation</a></li>
  <li><a href="#users-page-implementation">Users Page Implementation</a></li>
  <li><a href="#users-component-implementation">Users Component Implementation</a></li>
  <li><a href="#modify-the-home-page">Modify the Home Page</a></li>
  <li><a href="#add-a-menu-to-the-app">Add a Menu to the App</a></li>
  <li><a href="#update-config-and-packagejson-scripts">Update Config and Package.json Scripts</a></li>
  <li><a href="#run-the-web-sqlite-app">Run the Web SQLite App</a></li>
  <li><a href="#part-1-conclusion">Part 1 Conclusion</a></li>
</ul>

<hr />

<h3 id="install-new-ionic-application">Install New Ionic Application</h3>

<ul>
  <li>
    <p>Install the latest version of Ionic CLI globally installed on your device, run the below command.</p>

    <pre><code class="language-bash"> sudo npm install -g @ionic/cli
 sudo npm install -g npm install g generate-react-cli
</code></pre>
  </li>
  <li>
    <p>Create a new blank Ionic React app</p>

    <pre><code class="language-bash"> ionic start ionic7-react-sqlite-app blank --type=react --capacitor
</code></pre>
  </li>
  <li>
    <p>Go inside the project folder</p>

    <pre><code class="language-bash"> cd ./ionic7-react-sqlite-app
</code></pre>
  </li>
</ul>

<h3 id="install-required-packages">Install Required Packages</h3>

<ul>
  <li>
    <p>run the below commands</p>

    <pre><code class="language-bash"> npm install --save @capacitor-community/sqlite
 npm install --save @capacitor/toast
 npm install --save @ionic/pwa-elements
 npm install --save-dev copyfiles
</code></pre>
  </li>
</ul>

<h3 id="create-a-react-cli-config-file">Create a React Cli Config file</h3>

<ul>
  <li>
    <p>In your editor, create a <code>generate-react-cli.json</code> file and includes the following code:</p>

    <pre><code class="language-json"> {
 "usesTypeScript": true,
 "usesStyledComponents": false,
 "testLibrary": "None",
 "component": {
     "default": {
     "path": "src/components",
     "withStyle": true,
     "withTest": false,
     "withStory": false,
     "withLazy": false
     }
 },
 "usesCssModule": false,
 "cssPreprocessor": "css"
 }
</code></pre>
  </li>
</ul>

<h3 id="create-the-sqlite-database">Create the SQLite Database</h3>

<ul>
  <li>
    <p>To easily upgrade the database from one version to the next, the database is created through an upgrade statement. In your editor, create a folder <code>upgrades</code> under the <code>src</code> folder and then create a new file <code>upgrades/user.upgrade.statements.ts</code>.</p>
  </li>
  <li>
    <p>Define the upgrade statements in <code>upgrades/user.upgrade.statements.ts</code> file</p>

    <pre><code class="language-ts"> export const UserUpgradeStatements = [
     {
     toVersion: 1,
     statements: [
         `CREATE TABLE IF NOT EXISTS users (
         id INTEGER PRIMARY KEY AUTOINCREMENT,
         name TEXT NOT NULL,
         active INTEGER DEFAULT 1
         );`
     ]
     },
     /* add new statements below for next database version when required*/
     /*
     {
     toVersion: 2,
     statements: [
         `ALTER TABLE users ADD COLUMN email TEXT;`,
     ]
     },
     */
 ]
   
</code></pre>
  </li>
  <li>
    <p>Define the User Model</p>

    <p>In your editor, create a folder <code>models</code> under the <code>src</code> folder and then create a new file <code>models/user.ts</code>.</p>
  </li>
  <li>
    <p>Update the <code>models/user.ts</code> file as</p>

    <pre><code class="language-ts"> export interface User {
     id: number
     name: string
     active: number
     /* for version 2
     email: string
     */
 }
</code></pre>
  </li>
</ul>

<h3 id="create-crud-and-sqlite-services">Create CRUD and SQLite Services</h3>

<ul>
  <li>
    <p>To create CRUD and SQLite services, in your file editor, add a new <code>src/services</code> folder and create the two following files:</p>

    <ul>
      <li><code>services/sqliteService.ts</code></li>
      <li><code>services/storageService.ts</code></li>
    </ul>
  </li>
  <li>
    <p>Open the <code>services/sqliteService.ts</code> file and replace with the following code.</p>

    <pre><code class="language-ts"> import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection, capSQLiteUpgradeOptions } from '@capacitor-community/sqlite';
 import { Capacitor } from '@capacitor/core';

 export interface ISQLiteService {
     getPlatform(): string
     initWebStore(): Promise&lt;void&gt;
     addUpgradeStatement(options: capSQLiteUpgradeOptions): Promise&lt;void&gt; 
     openDatabase(dbName: string, loadToVersion: number, readOnly: boolean): Promise&lt;SQLiteDBConnection&gt; 
     closeDatabase(dbName: string, readOnly: boolean): Promise&lt;void&gt;
     saveToStore(dbName: string): Promise&lt;void&gt;
     saveToLocalDisk(dbName: string): Promise&lt;void&gt;
     isConnection(dbName: string, readOnly: boolean): Promise&lt;boolean&gt;
 };

 class SQLiteService implements ISQLiteService {
     platform = Capacitor.getPlatform();
     sqlitePlugin = CapacitorSQLite;
     sqliteConnection = new SQLiteConnection(CapacitorSQLite);
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     getPlatform(): string {
         return this.platform;
     }
     async initWebStore() : Promise&lt;void&gt;  {
         try {
             await this.sqliteConnection.initWebStore();
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.initWebStore: ${msg}`);
         }
         return;
     }
     async addUpgradeStatement(options: capSQLiteUpgradeOptions): Promise&lt;void&gt; {
         try {
             await this.sqlitePlugin.addUpgradeStatement(options);
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.addUpgradeStatement: ${msg}`);
         }
         return;
     }
     async openDatabase(dbName:string, loadToVersion: number,
                 readOnly: boolean): Promise&lt;SQLiteDBConnection&gt;  {
         this.dbNameVersionDict.set(dbName, loadToVersion);
         let encrypted = false;
         const mode = encrypted ? "secret" : "no-encryption";
         try {
             let db: SQLiteDBConnection;
             const retCC = (await this.sqliteConnection.checkConnectionsConsistency()).result;
             let isConn = (await this.sqliteConnection.isConnection(dbName, readOnly)).result;
             if(retCC &amp;&amp; isConn) {
             db = await this.sqliteConnection.retrieveConnection(dbName, readOnly);
             } else {
                 db = await this.sqliteConnection
                         .createConnection(dbName, encrypted, mode, loadToVersion, readOnly);
             }
             const jeepSQlEL = document.querySelector("jeep-sqlite")
        
             await db.open();
             const res = await db.isDBOpen();
             return db;
            
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.openDatabase: ${msg}`);
         }

     }
     async isConnection(dbName:string, readOnly: boolean): Promise&lt;boolean&gt; {
         try {
             const isConn = (await this.sqliteConnection.isConnection(dbName, readOnly)).result;
             if (isConn != undefined) {
                 return isConn
             } else {
                 throw new Error(`sqliteService.isConnection undefined`);
             }
            
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.isConnection: ${msg}`);
         }
     }
     async closeDatabase(dbName:string, readOnly: boolean):Promise&lt;void&gt; {
         try {
             const isConn = (await this.sqliteConnection.isConnection(dbName, readOnly)).result;
             if(isConn) {
                 await this.sqliteConnection.closeConnection(dbName, readOnly);
             }
             return;
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.closeDatabase: ${msg}`);
         }
     }
     async saveToStore(dbName: string): Promise&lt;void&gt; {
         try {
             await this.sqliteConnection.saveToStore(dbName);
             return;
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`sqliteService.saveToStore: ${msg}`);
         }
     }
     async saveToLocalDisk(dbName: string): Promise&lt;void&gt; {
         try {
             await this.sqliteConnection.saveToLocalDisk(dbName);
             return;
         } catch(err:any) {
             const msg = err.message ? err.message : err;
             throw new Error(`sqliteService.saveToLocalDisk: ${msg}`);
         }
     }
 }
 export default new SQLiteService();
</code></pre>
  </li>
  <li>
    <p>Open the <code>services/storageService.ts</code> and replace the code with</p>

    <pre><code class="language-ts"> import {platform} from '../App';
 import { BehaviorSubject } from 'rxjs';
 import {ISQLiteService } from '../services/sqliteService'; 
 import {IDbVersionService } from '../services/dbVersionService';
 import { SQLiteDBConnection } from '@capacitor-community/sqlite';
 import { UserUpgradeStatements } from '../upgrades/user.upgrade.statements';
 import { User } from '../models/User';

 export interface IStorageService {
     initializeDatabase(): Promise&lt;void&gt;
     getUsers(): Promise&lt;User[]&gt;
     addUser(user: User): Promise&lt;number&gt;
     updateUserById(id: string, active: number): Promise&lt;void&gt; 
     deleteUserById(id: string): Promise&lt;void&gt;
     getDatabaseName(): string
     getDatabaseVersion(): number
 };
 class StorageService implements IStorageService  {
     versionUpgrades = UserUpgradeStatements;
     loadToVersion = UserUpgradeStatements[UserUpgradeStatements.length-1].toVersion;
     db!: SQLiteDBConnection;
     database: string = 'myuserdb';
     sqliteServ!: ISQLiteService;
     dbVerServ!: IDbVersionService;
     isInitCompleted = new BehaviorSubject(false);

     constructor(sqliteService: ISQLiteService, dbVersionService: IDbVersionService) {
         this.sqliteServ = sqliteService;
         this.dbVerServ = dbVersionService;
     }
        
     getDatabaseName(): string {
         return this.database;
     }
     getDatabaseVersion(): number {
         return this.loadToVersion;
     }
     async initializeDatabase(): Promise&lt;void&gt; {
         // create upgrade statements
         try {
             await this.sqliteServ.addUpgradeStatement({database: this.database,
                                                 upgrade: this.versionUpgrades});
             this.db = await this.sqliteServ.openDatabase(this.database, this.loadToVersion, false);
             const isData = await this.db.query("select * from sqlite_sequence");
             if(isData.values!.length === 0) {
             // create database initial users if any

             }

             this.dbVerServ.setDbVersion(this.database,this.loadToVersion);
             if( platform === 'web') {
             await this.sqliteServ.saveToStore(this.database);
             }
             this.isInitCompleted.next(true);
         } catch(error: any) {
             const msg = error.message ? error.message : error;
             throw new Error(`storageService.initializeDatabase: ${msg}`);
         }
     }
     async getUsers(): Promise&lt;User[]&gt;  {
         return (await this.db.query('SELECT * FROM users;')).values as User[];
     }
     async addUser(user: User): Promise&lt;number&gt; {
         const sql = `INSERT INTO users (name) VALUES (?);`;
         const res = await this.db.run(sql,[user.name]);
         if (res.changes !== undefined
             &amp;&amp; res.changes.lastId !== undefined &amp;&amp; res.changes.lastId &gt; 0) {
             return res.changes.lastId;
         } else {
             throw new Error(`storageService.addUser: lastId not returned`);
         }
     }
     async updateUserById(id: string, active: number): Promise&lt;void&gt; {
         const sql = `UPDATE users SET active=${active} WHERE id=${id}`;
         await this.db.run(sql);
     }
     async deleteUserById(id: string): Promise&lt;void&gt; {
         const sql = `DELETE FROM users WHERE id=${id}`;
         await this.db.run(sql);
     }

 }
 export default StorageService;
</code></pre>
  </li>
</ul>

<p>To manage the database versionning, a new service <code>DbnameVersionService</code> is required. In your file editor, go to <code>src/services</code> folder and create the <code>dbVersionService.ts</code> file</p>

<ul>
  <li>
    <p>Open the <code>services/dbVersionService.ts</code> file and replace the code with</p>

    <pre><code class="language-ts"> export interface IDbVersionService {
     setDbVersion(dbName: string, version: number): void
     getDbVersion(dbName: string):number| undefined
 };
 class DbVersionService implements IDbVersionService  {
     dbNameVersionDict: Map&lt;string, number&gt; = new Map();

     setDbVersion(dbName: string, version: number) {
         this.dbNameVersionDict.set(dbName, version);
     };
     getDbVersion(dbName: string): number | undefined {
         const version =  this.dbNameVersionDict.get(dbName);
         return version;
     };
 }
 export default new DbVersionService();
</code></pre>
  </li>
</ul>

<h3 id="react-plugin-implementation">React Plugin Implementation</h3>

<p>For Web applications, the plugin uses the Stencil component <code>jeep-sqlite</code> which implies some react files modification</p>

<ul>
  <li>
    <p>Open the <code>main.tsx</code> file and replace the code with the following</p>

    <pre><code class="language-ts"> import React from 'react';
 import { createRoot } from 'react-dom/client';
 import App from './App';

 import { Capacitor } from '@capacitor/core';
 import { JeepSqlite } from 'jeep-sqlite/dist/components/jeep-sqlite';
 import { defineCustomElements as pwaElements} from '@ionic/pwa-elements/loader';

 pwaElements(window);
 customElements.define('jeep-sqlite', JeepSqlite);
 const platform = Capacitor.getPlatform();

 const rootRender = () =&gt; {
     const container = document.getElementById('root');
     const root = createRoot(container!);
     root.render(
         &lt;React.StrictMode&gt;
         &lt;App /&gt;
         &lt;/React.StrictMode&gt;
     );
 }
 if (platform !== "web") {
     rootRender();
 } else {
     window.addEventListener('DOMContentLoaded', async () =&gt; {
         const jeepEl = document.createElement("jeep-sqlite");
         document.body.appendChild(jeepEl);
         customElements.whenDefined('jeep-sqlite').then(() =&gt; {
             rootRender();
         })
         .catch ((err) =&gt; {
             console.log(`Error: ${err}`);
             throw new Error(`Error: ${err}`)
         });
     });
 }
</code></pre>
  </li>
  <li>
    <p>To initialize the application, an <code>AppInitializer</code> React component is used and has to be created</p>

    <pre><code class="language-bash"> npx generate-react-cli component AppInitializer
</code></pre>
  </li>
  <li>
    <p>In your editor, open the file <code>components/AppInitializer/AppInitializer.tsx</code> and replace the code with:</p>

    <pre><code class="language-ts"> import { FC, useEffect, useContext, useRef } from 'react';
 import { Toast } from '@capacitor/toast';
 import './AppInitializer.css';
 import InitializeAppService  from '../../services/initializeAppService';
 import { SqliteServiceContext, StorageServiceContext } from '../../App';

 interface AppInitializerProps {
     children : any
 }

 const AppInitializer: FC&lt;AppInitializerProps&gt; = ({ children }) =&gt; {
     const ref = useRef(false);
     const sqliteService = useContext(SqliteServiceContext);
     const storageService = useContext(StorageServiceContext);
     const initializeAppService = new InitializeAppService(sqliteService,
                                                             storageService);
     useEffect(()=&gt; {
         const initApp = async ():Promise &lt;void&gt; =&gt; {
             try {
                 const appInit = await initializeAppService.initializeApp();
                 return;
             } catch(error: any) {
                 const msg = error.message ? error.message : error;
                 Toast.show({
                 text: `${msg}`,
                 duration: 'long'
                 });           
             }  
         };
         if(ref.current === false) {
             initApp();
             ref.current = true;
         }

     }, []);

     return &lt;&gt;{children}&lt;/&gt;;
 };

 export default AppInitializer;
</code></pre>
  </li>
</ul>

<p>The <code>AppInitializer</code> component is defined using the FC type. It takes children as a prop and uses the useEffect hook to run the initialization logic when the component mounts. The {children} element is used to render the wrapped components passed as children in fact here the application. 
 To make the code more modular and easier to maintain, the <code>AppInitializer</code> component then simply calls the <code>initializeApp</code> method from the <code>initializeService</code> to perform the necessary initialization tasks.</p>

<ul>
  <li>
    <p>Create  in your Editor the <code>services/initializeService.ts</code> file and replace the code with</p>

    <pre><code class="language-ts"> import {platform} from '../App';
 import {ISQLiteService } from '../services/sqliteService'; 
 import {IStorageService } from '../services/storageService'; 

 export interface IInitializeAppService {
     initializeApp(): Promise&lt;boolean&gt;
 };

 class InitializeAppService implements IInitializeAppService  {
     appInit = false;
     sqliteServ!: ISQLiteService;
     storageServ!: IStorageService;

     constructor(sqliteService: ISQLiteService, storageService: IStorageService) {
         this.sqliteServ = sqliteService;
         this.storageServ = storageService;
     }
     async initializeApp() : Promise&lt;boolean&gt; {
         if(!this.appInit) {
             try {
                 if (platform === 'web') {
                     const jeepSQlEL = document.querySelector("jeep-sqlite")
                     await this.sqliteServ.initWebStore();
                 }
                 // Initialize the myuserdb database
                 await this.storageServ.initializeDatabase();
                 if( platform === 'web') {
                     await this.sqliteServ.saveToStore(this.storageServ.getDatabaseName());
                 }
                 this.appInit = true;
             } catch(error: any) {
                 const msg = error.message ? error.message : error;
                 throw new Error(`initializeAppError.initializeApp: ${msg}`);
             }
         }
         return this.appInit;
     }
 }
 export default InitializeAppService;
</code></pre>
  </li>
  <li>
    <p>Finally open the <code>App.tsx</code> file  and replace the code with</p>

    <pre><code class="language-ts"> import React from 'react';
 import { Redirect, Route } from 'react-router-dom';
 import { IonApp, IonRouterOutlet, setupIonicReact } from '@ionic/react';
 import { IonReactRouter } from '@ionic/react-router';
 import Home from './pages/Home';
 import { Capacitor } from '@capacitor/core';
 import SqliteService from './services/sqliteService';
 import DbVersionService from './services/dbVersionService';
 import StorageService  from './services/storageService';
 import AppInitializer from './components/AppInitializer/AppInitializer';

 import UsersPage from './pages/UsersPage/UsersPage';
 import AppMenu from './components/AppMenu/AppMenu';

 /* Core CSS required for Ionic components to work properly */
 import '@ionic/react/css/core.css';

 /* Basic CSS for apps built with Ionic */
 import '@ionic/react/css/normalize.css';
 import '@ionic/react/css/structure.css';
 import '@ionic/react/css/typography.css';

 /* Optional CSS utils that can be commented out */
 import '@ionic/react/css/padding.css';
 import '@ionic/react/css/float-elements.css';
 import '@ionic/react/css/text-alignment.css';
 import '@ionic/react/css/text-transformation.css';
 import '@ionic/react/css/flex-utils.css';
 import '@ionic/react/css/display.css';

 /* Theme variables */
 import './theme/variables.css';

 export const platform = Capacitor.getPlatform();

 // Singleton Services
 export const SqliteServiceContext = React.createContext(SqliteService);
 export const DbVersionServiceContext = React.createContext(DbVersionService);
 export const StorageServiceContext = React.createContext(new StorageService(SqliteService,DbVersionService));


 setupIonicReact();

 const App: React.FC = () =&gt; {
     return (
         &lt;SqliteServiceContext.Provider value={SqliteService}&gt;
             &lt;DbVersionServiceContext.Provider value={DbVersionService}&gt;
                 &lt;StorageServiceContext.Provider value={new StorageService(SqliteService,DbVersionService)}&gt;
                     &lt;AppInitializer&gt;
                         &lt;IonApp&gt;
                         &lt;IonReactRouter&gt;
                             &lt;AppMenu /&gt;
                             &lt;IonRouterOutlet id="main-content"&gt;
                             &lt;Route exact path="/home"&gt;
                                 &lt;Home /&gt;
                             &lt;/Route&gt;
                             &lt;Route exact path="/"&gt;
                                 &lt;Redirect to="/home" /&gt;
                             &lt;/Route&gt;
                             &lt;Route path="/users" component={UsersPage} /&gt;
                             &lt;/IonRouterOutlet&gt;
                         &lt;/IonReactRouter&gt;
                         &lt;/IonApp&gt;
                     &lt;/AppInitializer&gt;
                 &lt;/StorageServiceContext.Provider&gt;
             &lt;/DbVersionServiceContext.Provider&gt;
         &lt;/SqliteServiceContext.Provider&gt;
     )
 };

 export default App;
</code></pre>
    <p>As the goal is to ensure that the services (<code>SqliteService</code>, <code>DbVersionService</code> and <code>StorageService</code>) are unique and properly shared and available throughout the components, a Context Provider was created for Each Service.</p>
  </li>
</ul>

<p>By wrapping your App component structure with the context providers and the AppInitializer component, you ensure that the services are available to all components within your app. The dependency injection mechanism will ensure that you’ll have access to your shared services in both the HomePage and the UsersPage, as well as any other components that you include in your routes or other parts of your app in the future.</p>

<h3 id="users-page-implementation">Users Page Implementation</h3>

<p>As you can see above, a route <code>/users</code> to a <code>UsersPage</code> has been added.
 Let’s create it.</p>

<ul>
  <li>
    <p>In your Editor, create a new folder <code>UsersPage</code> under pages folder and in that new folder create two files <code>UsersPage.css</code> and <code>UsersPage.tsx</code>.</p>
  </li>
  <li>
    <p>Then open the <code>UsersPage.tsx</code> file and add the following code:</p>

    <pre><code class="language-ts"> import { useState, useEffect, useRef, useContext } from 'react';
 import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonCard,
         IonButtons, IonBackButton, useIonViewWillEnter, useIonViewWillLeave
     } from '@ionic/react';
 import './UsersPage.css';
 import UserForm from '../../components/UserForm/UserForm';
 import UserList from '../../components/UserList/UserList';
 import { User } from '../../models/User';
 import { useQuerySQLite } from '../../hooks/UseQuerySQLite';
 import { SQLiteDBConnection } from "@capacitor-community/sqlite";
 import { platform } from '../../App';
 import { SqliteServiceContext, StorageServiceContext } from '../../App';
 import { Toast } from '@capacitor/toast';

 const UsersPage: React.FC = () =&gt; {
     const ref = useRef(false);
     const dbNameRef = useRef('');
     const isInitComplete = useRef(false);
     const [users, setUsers] = useState&lt;User[]&gt;([]);
     const [db, setDb] = useState&lt;SQLiteDBConnection | null&gt;(null);
     const sqliteServ = useContext(SqliteServiceContext);
     const storageServ = useContext(StorageServiceContext);

     const openDatabase = () =&gt; {
         try {
             const dbUsersName = storageServ.getDatabaseName();
             dbNameRef.current = dbUsersName;
             const version = storageServ.getDatabaseVersion();

             sqliteServ.openDatabase(dbUsersName, version, false).then((database) =&gt; {
                 setDb(database);
                 ref.current = true;
             });
         } catch (error) {
             const msg = `Error open database:: ${error}`;
             console.error(msg);
             Toast.show({
                 text: `${msg}`,
                 duration: 'long'
             });           
         }
     }

     const handleAddUser = async (newUser: User) =&gt; {
         if (db) {
             // Send the newUser to the addUser storage service method
             const isConn = await sqliteServ.isConnection(dbNameRef.current,false);
             const lastId = await storageServ.addUser(newUser);
             newUser.id = lastId;

             // Update the users state to include the newly added user
             setUsers(prevUsers =&gt; [...prevUsers, newUser]);

         }
     };

     const handleUpdateUser = async (updUser: User) =&gt; {
         if (db) {
             const isConn = await sqliteServ.isConnection(dbNameRef.current,false);
             await storageServ.updateUserById(updUser.id.toString(),updUser.active);
             // Update the users state with the modified user
             setUsers(prevUsers =&gt;
                 prevUsers.map(user =&gt;
                 user.id === updUser.id ? { ...user, active: updUser.active } : user
                 )
             );
         }
     };

     const handleDeleteUser = async (userId: number) =&gt; {
         if (db) {
             const isConn = await sqliteServ.isConnection(dbNameRef.current,false);
             await storageServ.deleteUserById(userId.toString());
             // Update the users state by filtering out the deleted user
             setUsers(prevUsers =&gt; prevUsers.filter(user =&gt; user.id !== userId));
         }
     };

     useIonViewWillEnter( () =&gt; {
         const initSubscription = storageServ.isInitCompleted.subscribe  ((value) =&gt; {
             isInitComplete.current = value;
             if(isInitComplete.current === true) {
                 const dbUsersName = storageServ.getDatabaseName();
                 if(ref.current === false) {
                     if(platform === "web") {
                         customElements.whenDefined('jeep-sqlite').then(() =&gt; {
                             openDatabase();
                         })
                         .catch ((error) =&gt; {
                             const msg = `Error open database:: ${error}`;
                             console.log(`msg`);
                             Toast.show({
                                 text: `${msg}`,
                                 duration: 'long'
                             });           
                         });
                     } else {
                         openDatabase();
                     }
                 }
             }
         });

         return () =&gt; {
             initSubscription.unsubscribe();
         };
     }, [storageServ]);

     useIonViewWillLeave(  () =&gt; {

         sqliteServ.closeDatabase(dbNameRef.current,false).then(() =&gt; {
             ref.current = false;  
         })
         .catch((error) =&gt; {
             const msg = `Error close database:: ${error}`;
             console.error(msg);
             Toast.show({
             text: `${msg}`,
             duration: 'long'
             });           
         });
     });
     useEffect(() =&gt; {
         // Fetch users from the database using useQuerySQLite hook

         if (isInitComplete.current === true &amp;&amp; db) {
             const stmt = 'SELECT * FROM users';
             const values: any[] = [];
             const fetchData =  useQuerySQLite(db, stmt, values);
             fetchData()
             .then((fetchedUserData) =&gt; {
                 setUsers(fetchedUserData);
             })
             .catch((error) =&gt; {
                 const msg = `Error fetching user data: ${error}`;
                 console.error(msg);
                 Toast.show({
                     text: `${msg}`,
                     duration: 'long'
                 });           
             });
         }
     }, [db]);


     return (
         &lt;IonPage&gt;
         &lt;IonHeader&gt;
             &lt;IonToolbar&gt;
             &lt;IonTitle&gt;Managing Users&lt;/IonTitle&gt;
             &lt;IonButtons slot="start"&gt;
                 &lt;IonBackButton text="home" defaultHref="/home"&gt;&lt;/IonBackButton&gt;
             &lt;/IonButtons&gt;
             &lt;/IonToolbar&gt;
         &lt;/IonHeader&gt;
         &lt;IonContent&gt;
             {ref.current &amp;&amp; (
             &lt;div&gt;
                 &lt;IonCard&gt;
                     &lt;h1&gt;Add New User&lt;/h1&gt;
                     &lt;UserForm onAddUser={handleAddUser} /&gt;
                 &lt;/IonCard&gt;
                 &lt;IonCard&gt;
                     &lt;h2&gt;Current Users&lt;/h2&gt;
                     &lt;UserList users={users} onUpdateUser={handleUpdateUser} 
                     onDeleteUser={handleDeleteUser}/&gt;
                 &lt;/IonCard&gt;
             &lt;/div&gt;
             )}
         &lt;/IonContent&gt;
         &lt;/IonPage&gt;
     );
 };

 export default UsersPage;
</code></pre>
  </li>
</ul>

<h3 id="users-component-implementation">Users Component Implementation</h3>

<p>In that tutorial we use a simple UI interface for CRUD operations through the use of a <code>UserForm</code> and a <code>UserList</code> React component.</p>

<ul>
  <li>
    <p>Run the below command</p>

    <pre><code class="language-bash"> npx generate-react-cli component UserForm
 npx generate-react-cli component UserList
</code></pre>
  </li>
  <li>
    <p>Open the <code>components/UserForm/UserForm.tsx</code> file and replace the code with</p>

    <pre><code class="language-ts"> import { FC, useState, useEffect, useRef } from 'react';
 import { User } from '../../models/User';
 import { IonInput, IonButton } from '@ionic/react';

 import './UserForm.css';

 interface UserFormProps {
     onAddUser: (user: User) =&gt; void;
 }

 const UserForm: FC&lt;UserFormProps&gt; = ({ onAddUser }) =&gt; {
     const isFormValid = useRef(false);
     const [name, setName] = useState('');
     const ionNameEl = useRef&lt;HTMLIonInputElement&gt;(null);

     /* for database Version 2
     const [email, setEmail] = useState('');
     const ionEmailEl = useRef&lt;HTMLIonInputElement&gt;(null);
     */

     const handleNameInput = (ev: Event) =&gt; {
         const value = (ev.target as HTMLIonInputElement).value as string;

         // Removes non alphanumeric characters
         const filteredValue = value.replace(/[^a-zA-Z0-9-' ']+/g, '');

         // Update both the state variable and
         //  the component to keep them in sync.
         setName(filteredValue);

         const inputCmp = ionNameEl.current;
         if (inputCmp !== null) {
             inputCmp.value = filteredValue;
         }

     };
     /* Version 2
     const handleEmailInput = (ev: Event) =&gt; {
         const value = (ev.target as HTMLIonInputElement).value as string;

         // Update both the state variable and
         // the component to keep them in sync.

         setEmail(value);

         const inputCmp = ionNameEl.current;
         if (inputCmp !== null) {
             inputCmp.value = value;
         }

     };
     */  

     const handleSubmit = () =&gt; {
         if (name /*&amp;&amp; email */) {
             const newUser: User = {
                 id: Date.now(), // do not care about the id value (generated by sqlite)
                 name,
                 active: 1,
                 /*email, //version 2 */
             };

             onAddUser(newUser);

             setName('');
             /*setEmail('');  // version 2 */
             isFormValid.current = false;
         }
     };
     const hasTwoWords = (input: string): boolean =&gt; {
         // Split the input string by spaces
         const words = input.trim().split(' ');

         // Check if there are exactly two non-empty words
         const isTwo = words.length === 2 &amp;&amp; words.every(word =&gt; word !== '');
         return isTwo;
     }

     /* Version 2
     const isValidEmail = (email: string): boolean =&gt; {
         if(email.length === 0){
             return false;
         }
         const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,}$/;
         const test = emailRegex.test(email);
         return test;
     }
     */
     useEffect(()=&gt; {
         (email) // version 2*/ ;
     }, [name /*, email // version 2*/]);

     return (
         &lt;div className="UserForm"&gt;
             &lt;IonInput
                 ref={ionNameEl}
                 type="text"
                 value={name}
                 onIonInput={handleNameInput}
                 placeholder="Rose Miller"
             &gt;&lt;/IonInput&gt;
             {/* version 2
             &lt;IonInput
                 ref={ionEmailEl}
                 type="email"
                 value={email}
                 onIonInput={handleEmailInput}
                 placeholder="Email"
             &gt;&lt;/IonInput&gt;
             */}
             &lt;IonButton expand="full" onClick={handleSubmit} disabled={!isFormValid.current}&gt;
                 Add User
             &lt;/IonButton&gt;
         &lt;/div&gt;
     )
 };

 export default UserForm;
</code></pre>
  </li>
  <li>
    <p>Open the <code>components/UserList/UserList.tsx</code> file and replace the code with</p>

    <pre><code class="language-ts"> import { FC } from 'react';
 import './UserList.css';
 import { IonList, IonItem, IonCheckbox, IonButton, IonIcon, IonLabel } from '@ionic/react';
 import { User } from '../../models/User';
 import { trash } from 'ionicons/icons'; // Import the trash icon

 interface UserListProps {
     users: User[],
     onUpdateUser: (user: User) =&gt; void;
     onDeleteUser: (userId: number) =&gt; void; 
 }

 const UserList: FC&lt;UserListProps&gt; = ({users, onUpdateUser, onDeleteUser}) =&gt; {
     const handleCheckboxChange = (user: User) =&gt; {
         // Create a new user object with the updated active value
         const updatedUser = { ...user, active: user.active === 1 ? 0 : 1 };
         onUpdateUser(updatedUser);
     };

     return (
         &lt;IonList className="UserList"&gt;
             { users.map((user: User) =&gt; (
                 &lt;IonItem key={user.id}&gt;
                     &lt;IonCheckbox
                         slot="start"
                         aria-label=""
                         checked={user.active === 1}
                         onIonChange={() =&gt; handleCheckboxChange(user)}&gt;
                     &lt;/IonCheckbox&gt;
                     {user.id} - {user.name}
                     &lt;IonButton
                         slot="end"
                         fill="clear"
                         color="danger"
                         onClick={() =&gt; onDeleteUser(user.id)}&gt;
                         &lt;IonIcon icon={trash} /&gt;
                     &lt;/IonButton&gt;
                 &lt;/IonItem&gt;
             ))}
         &lt;/IonList&gt;
     )
 };

 export default UserList;
</code></pre>
  </li>
</ul>

<h3 id="modify-the-home-page">Modify the Home Page</h3>

<p>The <code>Home</code> page will be modify to include:</p>

<pre><code>- a company logo
- a welcome text
- a menu to access application pages
</code></pre>

<p>This will be achieved by creating new React components that will be integrated in the <code>Home</code> page and for the menu component in the <code>App.tx</code> file</p>

<ul>
  <li>
    <p>Create an <code>AppLogo</code> React component</p>

    <pre><code class="language-bash"> npx generate-react-cli component AppLogo 
</code></pre>
    <ul>
      <li>
        <p>In your Editor replace the code of <code>AppLogo/AppLogo.tsx</code> with</p>

        <pre><code class="language-ts">  import React, { FC } from 'react';
  import './AppLogo.css';

  interface AppLogoProps {}

  const AppLogo: FC&lt;AppLogoProps&gt; = () =&gt; (
  &lt;div className="AppLogo"&gt;
      &lt;img src="assets/JeepQLogo.png" width="128" height="128" /&gt;
  &lt;/div&gt;
  );

  export default AppLogo;
</code></pre>
        <p>Obviously use your own logo and store it in the <code>public/assets</code> folder.</p>
      </li>
      <li>
        <p>In your Editor replace the code of <code>AppLogo/AppLogo.css</code> with</p>

        <pre><code class="language-css">  .AppLogo {
      width: 100%;
      max-height: 200px;
      display: flex;
      justify-content: center;
  }
</code></pre>
      </li>
    </ul>
  </li>
  <li>
    <p>Create an <code>AppIntroText</code> React component</p>

    <pre><code class="language-bash"> npx generate-react-cli component AppIntroText 
</code></pre>
    <ul>
      <li>
        <p>In your Editor replace the code of <code>AppIntroText/AppIntroText.tsx</code> with</p>

        <pre><code class="language-ts">  import React, { FC } from 'react';
  import './AppIntroText.css';

  interface AppIntroTextProps {}

  const AppIntroText: FC&lt;AppIntroTextProps&gt; = () =&gt; (
  &lt;div className="AppIntroText"&gt;
      &lt;h3&gt;
      Welcome to the Ionic7/React SQLite Database CRUD App Example Tutorial
      &lt;/h3&gt;
      &lt;h4&gt;using @capacitor-community/sqlite&lt;/h4&gt;
  &lt;/div&gt;
  );

  export default AppIntroText;
</code></pre>
        <p>Fill free to put whatever text you would like to see</p>
      </li>
      <li>
        <p>In your Editor replace the code of <code>AppIntroText/AppIntroText.css</code> with</p>

        <pre><code class="language-css">  .AppIntroText {
      margin: 100px;
      display: flex;
      flex-direction: column;
      text-align: center;
  }
</code></pre>
      </li>
    </ul>
  </li>
  <li>
    <p>Create an <code>AppMenuButton</code> React component</p>

    <pre><code class="language-bash"> npx generate-react-cli component AppMenuButton 
</code></pre>
    <ul>
      <li>
        <p>In your Editor replace the code of <code>AppMenuButton/AppMenuButton.tsx</code> with</p>

        <pre><code class="language-ts">  import { FC } from 'react';
  import './AppMenuButton.css';
  import { IonMenuButton } from '@ionic/react';

  interface AppMenuButtonProps {}

  const AppMenuButton: FC&lt;AppMenuButtonProps&gt; = () =&gt; {
  return (
      &lt;IonMenuButton slot="end" /&gt;
  )
  };

  export default AppMenuButton;
</code></pre>
      </li>
    </ul>
  </li>
  <li>
    <p>Then the <code>pages/Home.tsx</code> file can be modified as below to include all these components:</p>

    <pre><code class="language-ts"> import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/react';
 import AppLogo from '../components/AppLogo/AppLogo';
 import AppMenuButton from '../components/AppMenuButton/AppMenuButton';
 import './Home.css';
 import AppIntroText from '../components/AppIntroText/AppIntroText';

 const Home: React.FC = () =&gt; {
     return (
         &lt;IonPage&gt;
             &lt;IonHeader&gt;
                 &lt;IonToolbar&gt;
                     &lt;AppMenuButton /&gt;
                     &lt;IonTitle&gt;Home&lt;/IonTitle&gt;
                 &lt;/IonToolbar&gt;
             &lt;/IonHeader&gt;
             &lt;IonContent&gt;
                 &lt;AppLogo /&gt;
                 &lt;AppIntroText /&gt;
             &lt;/IonContent&gt;
         &lt;/IonPage&gt;
     );
 };

 export default Home;
</code></pre>
  </li>
</ul>

<h3 id="add-a-menu-to-the-app">Add a Menu to the App</h3>

<ul>
  <li>
    <p>For easy maintenance, the menu is implemented as a React component.</p>

    <pre><code class="language-bash"> npx generate-react-cli component AppMenu
</code></pre>
  </li>
  <li>
    <p>In your Editor, modify the <code>AppMenu/AppMenu.tsx</code> file</p>

    <pre><code class="language-ts"> import React, { FC } from 'react';
 import './AppMenu.css';
 import { IonMenu, IonHeader, IonToolbar, IonTitle, IonContent,
         IonList, IonItem, IonButton} from '@ionic/react';

 interface AppMenuProps {}

 const AppMenu: FC&lt;AppMenuProps&gt; = () =&gt; {
 const closeMenu = () =&gt; {
     const menu = document.querySelector('ion-menu');
     menu!.close();
 };

 return (
     &lt;IonMenu className="AppMenu" side="end" contentId="main-content"&gt;
         &lt;IonHeader&gt;
             &lt;IonToolbar&gt;
             &lt;IonTitle&gt;Menu Content&lt;/IonTitle&gt;
             &lt;/IonToolbar&gt;
         &lt;/IonHeader&gt;
         &lt;IonContent&gt;
             &lt;IonList&gt;
             &lt;IonItem onClick={closeMenu}&gt;
                 &lt;IonButton size="default" routerLink="/users" expand="full"&gt;Managing Users&lt;/IonButton&gt;
             &lt;/IonItem&gt;
             {/* ... other menu items */}
             &lt;/IonList&gt;
         &lt;/IonContent&gt;
     &lt;/IonMenu&gt;
 )
 };
 export default AppMenu;
</code></pre>
  </li>
  <li>
    <p>In your Editor, modify the <code>AppMenu/AppMenu.css</code> file</p>

    <pre><code class="language-css"> .AppMenu ion-button {
     --background: transparent;
     --color: initial;
     font-size: 18px;
 }
</code></pre>
  </li>
  <li>
    <p>Then modify the <code>App.tsx</code> file</p>
    <ul>
      <li>
        <p>by adding</p>

        <pre><code class="language-ts">  import AppMenu from './components/AppMenu/AppMenu';
</code></pre>
      </li>
      <li>
        <p>replace <code>&lt;IonRouterOutlet&gt;</code> with</p>

        <pre><code class="language-html">  &lt;AppMenu /&gt;
  &lt;IonRouterOutlet id="main-content"&gt;
</code></pre>
      </li>
    </ul>
  </li>
</ul>

<h3 id="update-config-and-packagejson-scripts">Update Config and Package.json Scripts</h3>

<ul>
  <li>
    <p>For Web application only the appID of the <code>capacitor.config.ts</code> must be amended with <code>YOUR_APP_ID</code></p>
  </li>
  <li>
    <p>For the <code>package .json</code> file</p>
    <ul>
      <li>
        <p>add the following script below <code>"build": "tsc &amp;&amp; vite build",</code>,</p>

        <pre><code class="language-json">  "copy:sql:wasm": "copyfiles -u 3 node_modules/sql.js/dist/sql-wasm.wasm public/assets",
  "ionic:serve:before": "npm run copy:sql:wasm",
</code></pre>
      </li>
      <li>
        <p>modify the <code>"dev": "vite",</code> with</p>

        <pre><code class="language-json">  "dev": "npm run copy:sql:wasm &amp;&amp; vite",
</code></pre>
      </li>
    </ul>
  </li>
</ul>

<h3 id="run-the-web-sqlite-app">Run the Web SQLite App</h3>

<ul>
  <li>
    <p>To run the Web app use the below command</p>

    <pre><code class="language-bash"> npm run dev
</code></pre>
  </li>
  <li>
    <p>In your favorite Browser enter</p>

    <pre><code> http://localhost:5173/
</code></pre>
  </li>
  <li>
    <p>This will bring you to the <code>Home</code> page</p>

    <div align="center"><br /><img src="/images/Ionic7-React-SQLite-HomePage.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p>To open the menu, click on the <span style="font-size: 24px;"><ion-icon name="menu"></ion-icon></span> icon in the top left corner.</p>

    <div align="center"><br /><img src="/images/Ionic7-React-SQLite-MenuOpen.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p> In the <strong><code>Menu Content</code></strong> click on <strong><code>MANAGING USERS</code></strong></p>

    <div align="center"><br /><img src="/images/Ionic7-React-SQLite-Managing-Users.png" width="250" /></div>
    <p><br /></p>
  </li>
</ul>

<p>On the screen-copy, ones has entered already some users.</p>
<ul>
  <li>To input new users
    <ul>
      <li>type a new user on the input field “Rose Miller”  under Name</li>
      <li>press on the <code>"Add User"</code> button will add the user.</li>
    </ul>
  </li>
  <li>
    <p>To update the <code>active</code>value for a user, press on the check icon on the left it will toggle the value from 1 to 0 or from 0 to 1.</p>
  </li>
  <li>
    <p>To delete a user press on the <code>trash</code> icon.</p>
  </li>
  <li>To save the database to store leave the <code>UsersPage</code> by going back <code>Home</code>.</li>
</ul>

<p>The database location can be see in the application tab of the development tools.</p>

<div align="center"><br /><img src="/images/Ionic7-React-SQLite-Database-Location.png" width="80%" /></div>
<p><br /></p>

<h3 id="part-1-conclusion">Part 1 Conclusion</h3>

<p>We have completed the Part 1 - Web application of the Ionic 7 SQLite Database CRUD App Example Tutorial using React and @capacitor-community/sqlite.</p>

<p>We learned how to implement the ‘@capacitor-community/sqlite’ plugin in the React Framework using standalone components on a Web platform.</p>

<p>We learned to use Context providers to ensure that the services are available to all components within the app.</p>

<p>We learned how to create an application menu.</p>

<p>We learned how to used some basic methods of the ‘@capacitor-community/sqlite’ plugin to create a CRUD application from scratched and store persistent SQLite data into the Web IndexedDB browser database.</p>

<p>Enjoy your development from there.</p>

<h2 id="part-2---native---table-of-contents">Part 2 - Native - Table of Contents</h2>

<hr />
<ul>
  <li><a href="#install-native-required-packages">Install Native Required Packages</a></li>
  <li><a href="#update-config-file">Update Config file</a></li>
  <li><a href="#update-packagejson-scripts">Update Package.json Scripts</a></li>
  <li><a href="#run-the-ios-app">Run the iOS App</a></li>
  <li><a href="#run-the-android-app">Run the Android App</a></li>
  <li><a href="#run-the-electron-app">Run the Electron App</a></li>
  <li><a href="#part-1-conclusion">Part 2 Conclusion</a></li>
</ul>

<hr />

<h3 id="install-native-required-packages">Install Native Required Packages</h3>

<ul>
  <li>
    <p>In order to build Android, iOS, or Electron applications on specific devices, it is necessary to install the necessary capacitor packages first. So run the following commands:</p>

    <pre><code class="language-bash"> npm install --save @capacitor/android
 npm install --save @capacitor/ios
 npm install --save @capacitor-community/electron
</code></pre>
  </li>
  <li>
    <p>Integrate the various platforms into the application.</p>

    <pre><code class="language-bash"> npm run build
 npx cap add android
 npx cap add ios
 npx cap add @capacitor-community/electron
</code></pre>
  </li>
</ul>

<h3 id="update-config-file">Update Config file</h3>

<p>The <code>capacitor.config.ts</code> file specifies parameters that the plugin needs, such as database location, database encryption, and the use of biometric authentication for access security. Such settings may be platform specific.</p>

<ul>
  <li>
    <p>Please modify the <code>capacitor.config.ts</code> file as below :</p>

    <pre><code class="language-ts"> import { CapacitorConfig } from '@capacitor/cli';

 const config: CapacitorConfig = {
 appId: 'YOUR_APP_ID',
 appName: 'YOUR_APP_NAME',
 webDir: 'dist',
 loggingBehavior: 'debug',
 server: {
     androidScheme: "http"
 },
 plugins: {
     CapacitorSQLite: {
     iosDatabaseLocation: 'Library/CapacitorDatabase',
     iosIsEncryption: false,
     iosKeychainPrefix: 'YOUR_APP_NAME',
     iosBiometric: {
         biometricAuth: false,
         biometricTitle : "Biometric login for capacitor sqlite"
     },
     androidIsEncryption: false,
     androidBiometric: {
         biometricAuth : false,
         biometricTitle : "Biometric login for capacitor sqlite",
         biometricSubTitle : "Log in using your biometric"
     },
     electronIsEncryption: false,
     electronWindowsLocation: "C:\\ProgramData\\CapacitorDatabases",
     electronMacLocation: "/Users/YOUR_NAME/CapacitorDatabases",
     electronLinuxLocation: "Databases"
     }
 }
 };
 export default config;
</code></pre>
  </li>
</ul>

<h3 id="update-packagejson-scripts">Update Package.json Scripts</h3>

<ul>
  <li>
    <p>First install a new package to remove the sql.js wasm file to reduce the native package size</p>

    <pre><code class="language-bash"> npm install --save-dev rimraf
</code></pre>
  </li>
  <li>
    <p>Open the <code>package.json</code> file and replace the scripts section with:</p>

    <pre><code class="language-json"> "scripts": {
     "dev": "npm run copy:sql:wasm &amp;&amp; vite",
     "build:web": "npm run copy:sql:wasm &amp;&amp; npm run build",
     "build:native": "npm run remove:sql:wasm &amp;&amp; npm run build",
     "build": "vite build",
     "preview": "vite preview",
     "copy:sql:wasm": "copyfiles -u 3 node_modules/sql.js/dist/sql-wasm.wasm public/assets",
     "remove:sql:wasm": "rimraf public/assets/sql-wasm.wasm",
     "ios:start": "npm run remove:sql:wasm &amp;&amp; npm run build:native &amp;&amp; npx cap sync &amp;&amp; npx cap copy &amp;&amp; npx cap open ios",
     "android:start": "npm run remove:sql:wasm &amp;&amp; npm run build:native &amp;&amp; npx cap sync &amp;&amp; npx cap copy &amp;&amp; npx cap open android",
     "electron:install": "cd electron &amp;&amp; npm install &amp;&amp; cd ..",
     "electron:prepare": "npm run remove:sql:wasm &amp;&amp; npm run build &amp;&amp; npx cap sync @capacitor-community/electron &amp;&amp; npx cap copy @capacitor-community/electron",
     "electron:start": "npm run electron:prepare &amp;&amp; cd electron &amp;&amp; npm run electron:start",
     "test.e2e": "cypress run",
     "test.unit": "vitest",
     "lint": "eslint"

 },
</code></pre>
  </li>
</ul>

<h3 id="run-the-ios-app">Run the iOS App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> npm run ios:start
</code></pre>
  </li>
  <li>
    <p>In Xcode wait for indexed file to complete, clean the project and run the app. You will get the following screen for the Home Page</p>

    <div align="center"><br /><img src="/images/Part2-iOS-Ionic7-React-SQLite-HomePage.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p>To open the menu, click on the <span style="font-size: 24px;"><ion-icon name="menu"></ion-icon></span> icon in the top left corner.</p>

    <div align="center"><br /><img src="/images/Part2-iOS-Ionic7-React-SQLite-MenuOpen.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p> In the <strong><code>Menu Content</code></strong> click on <strong><code>MANAGING USERS</code></strong></p>

    <div id="banner" style="overflow: hidden; display: flex; justify-content:space-around;">
 <div style="max-width: 40%;"><img src="/images/Part2-iOS-Ionic7-React-SQLite-Managing-Users-1.png" /></div>
 <div style="max-width: 38.1035%;"><img src="/images/Part2-iOS-Ionic7-React-SQLite-Managing-Users-2.png" /></div>
</div>
  </li>
</ul>

<p>On the screen-copies, ones has entered already some users.</p>
<ul>
  <li>To input new users
    <ul>
      <li>type a new user on the input field “Rose Miller”  under Name</li>
      <li>press on the <code>"Add User"</code> button will add the user.</li>
    </ul>
  </li>
  <li>
    <p>To update the <code>active</code>value for a user, press on the check icon on the left it will toggle the value from 1 to 0 or from 0 to 1.</p>
  </li>
  <li>
    <p>To delete a user press on the <code>trash</code> icon.</p>
  </li>
  <li>To leave the <code>UsersPage</code> by going back <code>Home</code>.</li>
</ul>

<h3 id="run-the-android-app">Run the Android App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> npm run android:start
</code></pre>
  </li>
  <li>
    <p>In Android Studio</p>

    <ul>
      <li>go to the menu Android/Preferences/Build, Execution, Deployment/Build Tools/Gradle and then select the gradle JDK <code>17 Oracle OpenJDK Version 17.0.7</code>. Then press <code>Apply</code> and <code>OK</code>.</li>
      <li>go to File/Sync Project With Gradle Files.</li>
      <li>go to Build/Clean Project.</li>
      <li>select your Emulator or Physical Device.</li>
      <li>run the app</li>
    </ul>
  </li>
  <li>
    <p>Screenshot of the screen for the Home page:</p>
  </li>
</ul>

<div align="center"><br /><img src="/images/Part2-Android-Ionic7-React-SQLite-HomePage.png" width="50%" /></div>
<p><br /></p>

<ul>
  <li>
    <p>To open the menu, click on the <span style="font-size: 24px;"><ion-icon name="menu"></ion-icon></span> icon in the top left corner.</p>

    <div align="center"><br /><img src="/images/Part2-Android-Ionic7-React-SQLite-MenuOpen.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p> In the <strong><code>Menu Content</code></strong> click on <strong><code>MANAGING USERS</code></strong></p>

    <div id="banner" style="overflow: hidden; display: flex; justify-content:space-around;">
 <div style="max-width: 40%;"><img src="/images/Part2-Android-Ionic7-React-SQLite-Managing-Users-1.png" /></div>
 <div style="max-width: 39.81%;"><img src="/images/Part2-Android-Ionic7-React-SQLite-Managing-Users-2.png" /></div>
</div>
  </li>
</ul>

<p>On the screen-copies, ones has entered already some users.</p>
<ul>
  <li>To input new users
    <ul>
      <li>type a new user on the input field “Rose Miller”  under Name</li>
      <li>press on the <code>"Add User"</code> button will add the user.</li>
    </ul>
  </li>
  <li>
    <p>To update the <code>active</code>value for a user, press on the check icon on the left it will toggle the value from 1 to 0 or from 0 to 1.</p>
  </li>
  <li>
    <p>To delete a user press on the <code>trash</code> icon.</p>
  </li>
  <li>To leave the <code>UsersPage</code> by going back <code>Home</code>.</li>
</ul>

<h3 id="run-the-electron-app">Run the Electron App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> cd electron
</code></pre>
  </li>
  <li>
    <p>Open the <code>package.json</code> file and replace the scripts:, dependencies:, devDependencies: sections with:</p>

    <pre><code class="language-json"> "scripts": {
     "build": "tsc &amp;&amp; electron-rebuild",
     "electron:start-live": "node ./live-runner.js",
     "electron:start": "npm run build &amp;&amp;  electron --inspect=5858 ./",
     "electron:pack": "npm run build &amp;&amp; electron-builder build --dir -c ./electron-builder.config.json",
     "electron:make": "npm run build &amp;&amp; electron-builder build -c ./electron-builder.config.json -p always"
 },
 "dependencies": {
     "@capacitor-community/electron": "^4.1.2",
     "@capacitor-community/sqlite": "^5.0.7",
     "better-sqlite3-multiple-ciphers": "^8.4.0",
     "chokidar": "~3.5.3",
     "crypto": "^1.0.1",
     "crypto-js": "^4.1.1",
     "electron-is-dev": "~2.0.0",
     "electron-json-storage": "^4.6.0",
     "electron-serve": "~1.1.0",
     "electron-unhandled": "~4.0.1",
     "electron-updater": "~5.0.1",
     "electron-window-state": "~5.0.3",
     "jszip": "^3.10.1",
     "node-fetch": "2.6.7"
 },
 "devDependencies": {
     "@types/better-sqlite3": "^7.6.4",
     "@types/crypto-js": "^4.1.1",
     "@types/electron-json-storage": "^4.5.0",
     "electron": "^25.2.0",
     "electron-builder": "^24.6.3",
     "electron-rebuild": "^3.2.9",
     "typescript": "~4.3.5"
 },

</code></pre>
  </li>
  <li>
    <p>In your Editor delete the <code>node_modules</code> folder and <code>package-lock.json</code> file.</p>
  </li>
  <li>
    <p>Then run the following commands:</p>

    <pre><code class="language-bash"> npm install
 cd ..
 npm run electron:start
</code></pre>
  </li>
  <li>
    <p>Screenshot of the screen for the Home page:</p>
  </li>
</ul>

<div align="center"><br /><img src="/images/Part2-Electron-Ionic7-React-SQLite-HomePage.png" width="50%" /></div>
<p><br /></p>

<ul>
  <li>
    <p>To open the menu, click on the <span style="font-size: 24px;"><ion-icon name="menu"></ion-icon></span> icon in the top left corner.</p>

    <div align="center"><br /><img src="/images/Part2-Electron-Ionic7-React-SQLite-MenuOpen.png" width="250" /></div>
    <p><br /></p>
  </li>
  <li>
    <p> In the <strong><code>Menu Content</code></strong> click on <strong><code>MANAGING USERS</code></strong></p>

    <div id="banner" style="overflow: hidden; display: flex; justify-content:space-around;">
 <div style="max-width: 40%;"><img src="/images/Part2-Electron-Ionic7-React-SQLite-Managing-Users-1.png" /></div>
 <div style="max-width: 39.84%;"><img src="/images/Part2-Electron-Ionic7-React-SQLite-Managing-Users-2.png" /></div>
</div>
  </li>
</ul>

<p>On the screen-copies, ones has entered already some users.</p>
<ul>
  <li>To input new users
    <ul>
      <li>type a new user on the input field “Rose Miller”  under Name</li>
      <li>press on the <code>"Add User"</code> button will add the user.</li>
    </ul>
  </li>
  <li>
    <p>To update the <code>active</code>value for a user, press on the check icon on the left it will toggle the value from 1 to 0 or from 0 to 1.</p>
  </li>
  <li>
    <p>To delete a user press on the <code>trash</code> icon.</p>
  </li>
  <li>To leave the <code>UsersPage</code> by going back <code>Home</code>.</li>
</ul>

<h3 id="part-2-conclusion">Part 2 Conclusion</h3>

<p>We have completed the Part 2 - Native and Electron applications of the Ionic 7 SQLite Database CRUD App Example Tutorial using React framework and @capacitor-community/sqlite.</p>

<p>We have learned to adapt the <code>capacitor.config.ts</code>file and the modify the scripts: section of the <code>package.json</code>file for native apps</p>

<p>We learned how to build and run the application for each native platforms.</p>

<p>Enjoy your development from there.</p>]]></content><author><name>Quéau Jean Pierre</name></author><category term="Other" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Ionic 7 SQLite Database CRUD App Example Tutorial using Angular and @capacitor-community/sqlite</title><link href="https://jepiqueau.github.io/2023/08/26/Ionic7Angular-SQLite-CRUD-App.html" rel="alternate" type="text/html" title="Ionic 7 SQLite Database CRUD App Example Tutorial using Angular and @capacitor-community/sqlite" /><published>2023-08-26T00:00:00+00:00</published><updated>2023-08-26T00:00:00+00:00</updated><id>https://jepiqueau.github.io/2023/08/26/Ionic7Angular-SQLite-CRUD-App</id><content type="html" xml:base="https://jepiqueau.github.io/2023/08/26/Ionic7Angular-SQLite-CRUD-App.html"><![CDATA[<hr />

<p><em>last updated on April 9, 2024 by Quéau Jean Pierre</em></p>

<p>In that tutorial we will learned how to create a Ionic7/Angular basic CRUD application and implement the @capacitor-community/sqlite plugin to store the data in a SQLite database.</p>

<p>The first part of the tutorial will concentrate on how to create that application and run it on a Web browser where the data will be stored on an Indexed database using sql.js and localForage modules.
Go to <a href="#part-1---web---table-of-contents">Part 1 - Web - Table of Contents</a></p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/SQLite/Part-1/ionic7-angular-sqlite-app">Part-1/ionic7-angular-sqlite-app</a></p>

<p>Thanks to the Ionic Team and their hard work to bring CAPACITOR 5, the second part will concentrate on native platforms (iOS and Android) and also on Electron platform.
Go to <a href="#part-2---native---table-of-contents">Part 2 - Native - Table of Contents</a></p>

<p>The application can be found at <a href="https://github.com/jepiqueau/blog-tutorials-apps/tree/main/SQLite/Part-2/ionic7-angular-sqlite-app">Part-2/ionic7-angular-sqlite-app</a></p>

<h2 id="part-1---web---table-of-contents">Part 1 - Web - Table of Contents</h2>

<hr />
<ul>
  <li><a href="#install-new-ionic-application">Install New Ionic Application</a></li>
  <li><a href="#install-required-packages">Install Required Packages</a></li>
  <li><a href="#create-the-sqlite-database">Create the SQLite Database</a></li>
  <li><a href="#create-crud-and-sqlite-services">Create CRUD and SQLite Services</a></li>
  <li><a href="#angular-plugin-implementation">Angular Plugin Implementation</a></li>
  <li><a href="#users-component-implementation">Users Component Implementation</a></li>
  <li><a href="#update-config-and-packagejson-scripts">Update Config and Package.json Scripts</a></li>
  <li><a href="#update-tsconfigjson">Update tsconfig.json</a></li>
  <li><a href="#update-angularjson">Update angular.json</a></li>
  <li><a href="#run-the-web-sqlite-app">Run the Web SQLite App</a></li>
  <li><a href="#part-1-conclusion">Part 1 Conclusion</a></li>
</ul>

<hr />

<h3 id="install-new-ionic-application">Install New Ionic Application</h3>

<ul>
  <li>
    <p>Install the latest version of Ionic CLI globally installed on your device, run the below command.</p>

    <pre><code class="language-bash"> sudo npm install -g @ionic/cli
</code></pre>
  </li>
  <li>
    <p>Create a new blank Ionic Angular app</p>

    <p>!!! Select standalone when asked !!!</p>

    <pre><code class="language-bash"> ionic start ionic7-angular-sqlite-app blank --type=angular --capacitor
</code></pre>
  </li>
  <li>
    <p>Go inside the project folder</p>

    <pre><code class="language-bash"> cd ./ionic7-angular-sqlite-app
</code></pre>
  </li>
</ul>

<h3 id="install-required-packages">Install Required Packages</h3>

<ul>
  <li>
    <p>run the below commands</p>

    <pre><code class="language-bash"> npm install --save @capacitor-community/sqlite
 npm install --save @capacitor/toast
 npm install --save @ionic/pwa-elements
 npm install --save-dev copyfiles
 npm install --save-dev crypto-browserify
 npm install --save-dev stream-browserify
 npm install --save-dev vm-browserify
</code></pre>
  </li>
</ul>

<h3 id="create-the-sqlite-database">Create the SQLite Database</h3>

<ul>
  <li>
    <p>To easily upgrade the database from one version to the next, the database is created through an upgrade statement.</p>

    <pre><code class="language-bash"> ng g class upgrades/user.upgrade.statements 
</code></pre>
  </li>
  <li>
    <p>Define the upgrade statements in <code>upgrades/user.upgrade.statements.ts</code> file</p>

    <pre><code class="language-ts"> export class UserUpgradeStatements {
     userUpgrades = [
         {
         toVersion: 1,
         statements: [
             `CREATE TABLE IF NOT EXISTS users(
             id INTEGER PRIMARY KEY AUTOINCREMENT,
             name TEXT NOT NULL,
             active INTEGER DEFAULT 1
             );`
         ]
         },
         /* add new statements below for next database version when required*/
         /*
         {
         toVersion: 2,
         statements: [
             `ALTER TABLE users ADD COLUMN email TEXT;`,
         ]
         },
         */
     ]
 }    
</code></pre>
  </li>
  <li>
    <p>Define the User Model</p>

    <pre><code class="language-bash"> ng g interface models/user
</code></pre>
  </li>
  <li>
    <p>update the <code>models/user.ts</code> file as</p>

    <pre><code class="language-ts"> export interface User {
     id: number
     name: string
     active: number
     /* for version 2
     email: string
     */
 }
</code></pre>
  </li>
</ul>

<h3 id="create-crud-and-sqlite-services">Create CRUD and SQLite Services</h3>

<ul>
  <li>
    <p>Run the following commands to create CRUD and SQLite services.</p>

    <pre><code class="language-bash"> ng g class services/sqlite.service
 ng g class services/storage.service
</code></pre>
  </li>
  <li>
    <p>Open the <code>services/sqlite.service.ts</code> file and replace with the following code.</p>

    <pre><code class="language-ts">     import { Injectable } from '@angular/core';

     import { Capacitor } from '@capacitor/core';
     import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection, CapacitorSQLitePlugin,
     capSQLiteUpgradeOptions, capSQLiteResult, capSQLiteValues} from '@capacitor-community/sqlite';

     @Injectable()

     export class SQLiteService {
         sqliteConnection!: SQLiteConnection;
         isService: boolean = false;
         platform!: string;
         sqlitePlugin!: CapacitorSQLitePlugin;
         native: boolean = false;
         constructor() {
         }
         /**
          * Plugin Initialization
          */
         async initializePlugin(): Promise&lt;boolean&gt; {
                 this.platform = Capacitor.getPlatform();
                 if(this.platform === 'ios' || this.platform === 'android') this.native = true;
                 this.sqlitePlugin = CapacitorSQLite;
                 this.sqliteConnection = new SQLiteConnection(this.sqlitePlugin);
                 this.isService = true;
                 return true;
         }

         async initWebStore(): Promise&lt;void&gt; {
             try {
             await this.sqliteConnection.initWebStore();
             } catch(err: any) {
             const msg = err.message ? err.message : err;
             return Promise.reject(`initWebStore: ${err}`);
             }
         }

         async openDatabase(dbName:string, encrypted: boolean, mode: string, version: number, readonly: boolean): Promise&lt;SQLiteDBConnection&gt; {
             let db: SQLiteDBConnection;
             const retCC = (await this.sqliteConnection.checkConnectionsConsistency()).result;
             let isConn = (await this.sqliteConnection.isConnection(dbName, readonly)).result;
             if(retCC &amp;&amp; isConn) {
                 db = await this.sqliteConnection.retrieveConnection(dbName, readonly);
             } else {
                 db = await this.sqliteConnection
                         .createConnection(dbName, encrypted, mode, version, readonly);
             }
             await db.open();
             return db;
         }
         async retrieveConnection(dbName:string, readonly: boolean): Promise&lt;SQLiteDBConnection&gt; {
             return await this.sqliteConnection.retrieveConnection(dbName, readonly);
         }
         async closeConnection(database:string, readonly?: boolean): Promise&lt;void&gt; {
             const readOnly = readonly ? readonly : false;
             return await this.sqliteConnection.closeConnection(database, readOnly);
         }
         async addUpgradeStatement(options:capSQLiteUpgradeOptions): Promise&lt;void&gt; {
             await this.sqlitePlugin.addUpgradeStatement(options);
             return;
         }
         async saveToStore(database:string) : Promise&lt;void&gt; {
             return await this.sqliteConnection.saveToStore(database);
         }
     }
</code></pre>
  </li>
  <li>
    <p>Open the <code>services/storage.service.ts</code> and replace the code with</p>

    <pre><code class="language-ts">     import { SQLiteDBConnection } from '@capacitor-community/sqlite';
     import { Injectable} from '@angular/core';
     import { SQLiteService } from './sqlite.service';
     import { DbnameVersionService } from './dbname-version.service';
     import { UserUpgradeStatements } from '../upgrades/user.upgrade.statements';
     import { User } from '../models/user';
     import { BehaviorSubject, Observable } from 'rxjs';

     @Injectable()
     export class StorageService {
         public userList: BehaviorSubject&lt;User[]&gt; =
                                     new BehaviorSubject&lt;User[]&gt;([]);
         private databaseName: string = "";
         private uUpdStmts: UserUpgradeStatements = new UserUpgradeStatements();
         private versionUpgrades;
         private loadToVersion;
         private db!: SQLiteDBConnection;
         private isUserReady: BehaviorSubject&lt;boolean&gt; = new BehaviorSubject(false);

         constructor(private sqliteService: SQLiteService,
                     private dbVerService: DbnameVersionService) {
             this.versionUpgrades = this.uUpdStmts.userUpgrades;
             this.loadToVersion = this.versionUpgrades[this.versionUpgrades.length-1].toVersion;
         }
         async initializeDatabase(dbName: string) {
             this.databaseName = dbName;
             // create upgrade statements
             await this.sqliteService
             .addUpgradeStatement({  database: this.databaseName,
                                     upgrade: this.versionUpgrades});
             // create and/or open the database
             this.db = await this.sqliteService.openDatabase(
                                                 this.databaseName,
                                                 false,
                                                 'no-encryption',
                                                 this.loadToVersion,
                                                 false
             );
             this.dbVerService.set(this.databaseName,this.loadToVersion);

             await this.getUsers();
         }
         // Current database state
         userState() {
             return this.isUserReady.asObservable();
         }
         fetchUsers(): Observable&lt;User[]&gt; {
             return this.userList.asObservable();
         }

         async loadUsers() {
             const users: User[]= (await this.db.query('SELECT * FROM users;')).values as User[];
             this.userList.next(users);
         }
         // CRUD Operations
         async getUsers() {
             await this.loadUsers();
             this.isUserReady.next(true);
         }
         async addUser(name: string) {
             const sql = `INSERT INTO users (name) VALUES (?);`;
             await this.db.run(sql,[name]);
             await this.getUsers();
         }

         async updateUserById(id: string, active: number) {
             const sql = `UPDATE users SET active=${active} WHERE id=${id}`;
             await this.db.run(sql);
             await this.getUsers();
         }
         async deleteUserById(id: string) {
             const sql = `DELETE FROM users WHERE id=${id}`;
             await this.db.run(sql);
             await this.getUsers();
         }
     }
</code></pre>
  </li>
</ul>

<p>To get the current database state, we imported RxJS BehaviorSubject and Observable properties and can extract the current database state by merely subscribing to them.</p>

<p>To manage the database versionning, a new service <code>DbnameVersionService</code> is required.</p>

<ul>
  <li>
    <p>Create it with</p>

    <pre><code class="language-bash"> ng g class services/dbname-version.service
</code></pre>
  </li>
  <li>
    <p>Open the <code>services/dbname-version.service.ts</code> file and replace the code with</p>

    <pre><code class="language-ts">     import { Injectable } from '@angular/core';

     @Injectable()
     export class DbnameVersionService {
         private _dbNameVersionDict: Map&lt;string, number&gt; = new Map();

         constructor() { }
         set(dbName: string, version: number) {
             this._dbNameVersionDict.set(dbName, version);

         }
         getVersion(dbName: string) {
             if (this._dbNameVersionDict.has(dbName)) {
             return this._dbNameVersionDict.get(dbName);
             } else {
             return -1;
             }
         }
     }
</code></pre>
  </li>
</ul>

<h3 id="angular-plugin-implementation">Angular Plugin Implementation</h3>

<p>For Web applications, the plugin uses the Stencil component <code>jeep-sqlite</code> which implies some angular files modification</p>

<ul>
  <li>
    <p>Open the <code>main.ts</code> file and replace the code with the following</p>

    <pre><code class="language-ts">     import { enableProdMode, importProvidersFrom, APP_INITIALIZER } from '@angular/core';
     import { bootstrapApplication } from '@angular/platform-browser';
     import { RouteReuseStrategy, provideRouter } from '@angular/router';
     import { IonicModule, IonicRouteStrategy } from '@ionic/angular';

     import { routes } from './app/app.routes';
     import { AppComponent } from './app/app.component';
     import { environment } from './environments/environment';
     import { defineCustomElements as pwaElements} from '@ionic/pwa-elements/loader';
     import { defineCustomElements as jeepSqlite} from 'jeep-sqlite/loader';
     import { Capacitor } from '@capacitor/core';
     import { InitializeAppService } from './app/services/initialize.app.service';
     import { SQLiteService } from './app/services/sqlite.service';
     import { StorageService } from './app/services/storage.service';
     import { DbnameVersionService } from './app/services/dbname-version.service';
   
     if (environment.production) {
         enableProdMode();
     }
     // --&gt; Below only required if you want to use a web platform
     const platform = Capacitor.getPlatform();
     if(platform === "web") {
         // Web platform
         // required for toast component in Browser
         pwaElements(window);

         // required for jeep-sqlite Stencil component
         // to use a SQLite database in Browser
         jeepSqlite(window);

         window.addEventListener('DOMContentLoaded', async () =&gt; {
             const jeepEl = document.createElement("jeep-sqlite");
             document.body.appendChild(jeepEl);
             await customElements.whenDefined('jeep-sqlite');
             jeepEl.autoSave = true;
         });
     }
     // Above only required if you want to use a web platform &lt;--
    
     // Define the APP_INITIALIZER factory
     export function initializeFactory(init: InitializeAppService) {
         return () =&gt; init.initializeApp();
     }

     bootstrapApplication(AppComponent, {
         providers: [SQLiteService,
             InitializeAppService,
             StorageService,
             DbnameVersionService,
             { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
             importProvidersFrom(IonicModule.forRoot({})),
             provideRouter(routes),
             {
             provide: APP_INITIALIZER,
             useFactory: initializeFactory,
             deps: [InitializeAppService],
             multi: true
             }
         ],
     });

</code></pre>
  </li>
  <li>
    <p>To initialize the application, an <code>InitializeAppService</code> is used and has to be created</p>

    <pre><code class="language-bash"> ng g class services/initialize.app.service
</code></pre>
  </li>
  <li>
    <p>Open the <code>services/initialize.app.service.ts</code> file and replace the code with</p>

    <pre><code class="language-ts"> import { Injectable } from '@angular/core';

 import { SQLiteService } from './sqlite.service';
 import { StorageService } from './storage.service';
 import { Toast } from '@capacitor/toast';

 @Injectable()
 export class InitializeAppService {
     isAppInit: boolean = false;
     platform!: string;

     constructor(
         private sqliteService: SQLiteService,
         private storageService: StorageService,
         ) {

     }

     async initializeApp() {
         await this.sqliteService.initializePlugin().then(async (ret) =&gt; {
             this.platform = this.sqliteService.platform;
             try {
                 if( this.sqliteService.platform === 'web') {
                     await this.sqliteService.initWebStore();
                 }
                 // Initialize the myuserdb database
                 const DB_USERS = 'myuserdb'
                 await this.storageService.initializeDatabase(DB_USERS);
                 // Here Initialize MOCK_DATA if required

                 // Initialize whatever database and/or MOCK_DATA you like

                 if( this.sqliteService.platform === 'web') {
                     await this.sqliteService.saveToStore(DB_USERS);
                 }

                 this.isAppInit = true;

             } catch (error) {
                 console.log(`initializeAppError: ${error}`);
                 await Toast.show({
                 text: `initializeAppError: ${error}`,
                 duration: 'long'
                 });
             }
         });
     }
 }
</code></pre>
  </li>
  <li>
    <p>Open the <code>app.component.ts</code> file  and replace the code with</p>

    <pre><code class="language-ts"> import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
 import { Component, EnvironmentInjector, inject } from '@angular/core';
 import { IonicModule } from '@ionic/angular';
 import { CommonModule } from '@angular/common';

 @Component({
 selector: 'app-root',
 templateUrl: 'app.component.html',
 styleUrls: ['app.component.scss'],
 standalone: true,
 imports: [IonicModule, CommonModule],
 schemas: [CUSTOM_ELEMENTS_SCHEMA]
 })
 export class AppComponent {
 public environmentInjector = inject(EnvironmentInjector);

 constructor() {}
 }
</code></pre>
  </li>
  <li>
    <p>open the <code>app.routes.ts</code> file and replace the code with</p>

    <pre><code class="language-ts"> import { Routes } from '@angular/router';

 export const routes: Routes = [
     {
         path: 'home',
         loadComponent: () =&gt; import('./home/home.page').then((m) =&gt; m.HomePage),
     },
     {
         path: '',
         redirectTo: 'home',
         pathMatch: 'full',
     },
 ];

</code></pre>
    <h3 id="users-component-implementation">Users Component Implementation</h3>
  </li>
</ul>

<p>In that tutorial we use a simple UI interface for CRUD operations through the use of an Angular users component.
 It can be easily modify to implement Reactive Forms.</p>

<ul>
  <li>
    <p>Run the below command</p>

    <pre><code class="language-bash"> ng g component components/users
</code></pre>
  </li>
  <li>
    <p>Open the <code>components/users/users.component.ts</code> file and replace the code with</p>

    <pre><code class="language-ts"> import { Component, OnInit } from '@angular/core';
 import { CommonModule } from '@angular/common';
 import { IonicModule } from '@ionic/angular';
 import { FormsModule} from '@angular/forms';
 import { StorageService } from '../../services/storage.service';
 import { User } from '../../models/user';
 import { of, switchMap } from 'rxjs';

 @Component({
 selector: 'app-users',
 templateUrl: './users.component.html',
 styleUrls: ['./users.component.scss'],
 imports: [CommonModule, IonicModule, FormsModule],
 standalone: true,
 })
 export class UsersComponent  implements OnInit {
 newUserName = ''
 userList: User[] = []
 isWeb: any

 constructor(private storage: StorageService) {}

 ngOnInit() {
     try {
         this.storage.userState().pipe(
             switchMap(res =&gt; {
             if (res) {
                 return this.storage.fetchUsers();
             } else {
                 return of([]); // Return an empty array when res is false
             }
             })
         ).subscribe(data =&gt; {
             this.userList = data; // Update the user list when the data changes
         });

         } catch(err) {
         throw new Error(`Error: ${err}`);
         }
     }
     async createUser() {
         await this.storage.addUser(this.newUserName)
         this.newUserName = ''
         console.log(this.userList, '#users')
     }

     updateUser(user: User) {
         const active = user.active === 0 ? 1 : 0
         this.storage.updateUserById(user.id.toString(), active)
     }

     deleteUser(user: User) {
         this.storage.deleteUserById(user.id.toString())
     }
 }
</code></pre>
  </li>
  <li>
    <p>Open the <code>components/users/users.components.html</code> file and replace the code with</p>

    <pre><code class="language-html"> &lt;ion-content&gt;

 &lt;ion-row&gt;
     &lt;ion-col size="9"&gt;
     &lt;ion-item&gt;
         &lt;ion-input
         label="Name" labelPlacement="stacked"
         placeholder="Rose Miller" [(ngModel)]="newUserName"
         &gt;
         &lt;/ion-input&gt;
     &lt;/ion-item&gt;
     &lt;/ion-col&gt;

     &lt;ion-col size="3"&gt;
     &lt;ion-button
     (click)="createUser()" expand="block" fill="outline"&gt;
         &lt;ion-icon name="add" slot="icon-only"&gt;&lt;/ion-icon&gt;
     &lt;/ion-button&gt;
     &lt;/ion-col&gt;
 &lt;/ion-row&gt;

 &lt;ion-item *ngFor="let user of userList"&gt;
     &lt;ion-checkbox
     aria-label="Label"
     slot="start"
     [ngModel]="user.active"
     (ionChange)="updateUser(user)" &gt;
     &lt;/ion-checkbox&gt;

     &lt;span&gt;
      -  - 
     &lt;/span&gt;

     &lt;ion-button slot="end" (click)="deleteUser(user)" fill="clear" color="danger"&gt;
     &lt;ion-icon name="trash" slot="icon-only"&gt;&lt;/ion-icon&gt;
     &lt;/ion-button&gt;
 &lt;/ion-item&gt;

 &lt;/ion-content&gt;
</code></pre>

    <p>!!! Caution Between the span tags
 You must read <code>Double left Curly Bracket</code> user.id <code>Double Right Curly Bracket</code> - <code>Double left Curly Bracket</code> user.name <code>Double Right Curly Bracket</code> -  <code>Double left Curly Bracket</code> user.active <code>Double Right Curly Bracket</code></p>
  </li>
  <li>
    <p>Now the <code>app-users</code> component can be used in the Home page. Open the <code>home/home.page.html</code> file  and replace the code with</p>

    <pre><code class="language-html"> &lt;ion-header [translucent]="true"&gt;
 &lt;ion-toolbar&gt;
     &lt;ion-title&gt;
     Managing Users
     &lt;/ion-title&gt;
 &lt;/ion-toolbar&gt;
 &lt;/ion-header&gt;

 &lt;ion-content [fullscreen]="true"&gt;
 &lt;ion-header collapse="condense"&gt;
     &lt;ion-toolbar&gt;
     &lt;ion-title size="large"&gt;Managing Users&lt;/ion-title&gt;
     &lt;/ion-toolbar&gt;
 &lt;/ion-header&gt;

 &lt;app-users&gt;&lt;/app-users&gt;
 &lt;/ion-content&gt;
</code></pre>
  </li>
  <li>
    <p>Then the <code>home.home.page.ts</code> file can be modified as below:</p>

    <pre><code class="language-ts"> import { Component } from '@angular/core';
 import { IonicModule } from '@ionic/angular';
 import { UsersComponent } from '../components/users/users.component';

 @Component({
 selector: 'app-home',
 templateUrl: 'home.page.html',
 styleUrls: ['home.page.scss'],
 standalone: true,
 imports: [IonicModule, UsersComponent ],
 })
 export class HomePage {
 constructor() {}
 }
</code></pre>
  </li>
</ul>

<h3 id="update-config-and-packagejson-scripts">Update Config and Package.json Scripts</h3>

<ul>
  <li>
    <p>For Web application only the appID of the <code>capacitor.config.ts</code> must be amended with <code>YOUR_APP_ID</code></p>
  </li>
  <li>
    <p>For the <code>package .json</code> file add the two following scripts below <code>"build": "ng build",</code>,</p>

    <pre><code class="language-json"> "ionic:serve:before": "npm run copy:sql:wasm",
 "copy:sql:wasm": "copyfiles -u 3 node_modules/sql.js/dist/sql-wasm.wasm src/assets",
</code></pre>
  </li>
</ul>

<h3 id="update-tsconfigjson">Update tsconfig.json</h3>

<ul>
  <li>In <code>compilerOptions</code> add the following</li>
</ul>

<pre><code class="language-json">     "paths":{
      "crypto":["node_modules/crypto-browserify"],
      "stream":["node_modules/stream-browserify"],
      "vm":["node_modules/vm-browserify"]
    }
</code></pre>

<h3 id="update-angularjson">Update angular.json</h3>

<ul>
  <li>In <code>architect</code> under <code>build</code> and <code>options</code> add <code>allowedCommonJsDependencies</code></li>
</ul>

<pre><code class="language-json"> {
    ...
  "architect": {
    "build": {
        ...
      "options": {
        "allowedCommonJsDependencies": ["crypto"],
        ...
      },
      ...
    }
  }
 }
</code></pre>

<ul>
  <li>Update all <code>browserTarget</code> with <code>buildTarget</code>.</li>
</ul>

<h3 id="run-the-web-sqlite-app">Run the Web SQLite App</h3>

<ul>
  <li>
    <p>To run the Web app use the below command</p>

    <pre><code class="language-bash"> ionic serve
</code></pre>
  </li>
</ul>

<p>This will bring you to the <code>Managing Users</code> page</p>

<div align="center"><br /><img src="/images/ionic7-Angular-SQLite-Managing-Users.png" width="250" /></div>
<p><br /></p>

<p>On the screen-copy, ones has entered already some users.</p>
<ul>
  <li>To input new users
    <ul>
      <li>type a new user on the input field “Rose Miller”  under Name</li>
      <li>press on the <code>"+"</code> button will add the user.</li>
    </ul>
  </li>
  <li>
    <p>To update the <code>active</code>value for a user, press on the check icon on the left it will toggle the value from 1 to 0 or from 0 to 1.</p>
  </li>
  <li>To delete a user press on the <code>trash</code> icon.</li>
</ul>

<p>The database location can be see in the application tab of the development tools.</p>

<div align="center"><br /><img src="/images/Ionic7-Angular-SQLite-Database-Location.png" width="80%" /></div>
<p><br /></p>

<h3 id="part-1-conclusion">Part 1 Conclusion</h3>

<p>We have completed the Part 1 - Web application of the Ionic 7 SQLite Database CRUD App Example Tutorial using Angular and @capacitor-community/sqlite.</p>

<p>We learned how to implement the ‘@capacitor-community/sqlite’ plugin in the Angular Framework using standalone components on a Web platform.</p>

<p>We learned how to used some basic methods of the ‘@capacitor-community/sqlite’ plugin to create a CRUD application from scratched and store persistent SQLite data into the Web IndexedDB browser database.</p>

<p>Enjoy your development from there.</p>

<h2 id="part-2---native---table-of-contents">Part 2 - Native - Table of Contents</h2>

<hr />
<ul>
  <li><a href="#install-native-required-packages">Install Native Required Packages</a></li>
  <li><a href="#update-config-file">Update Config file</a></li>
  <li><a href="#update-packagejson-scripts">Update Package.json Scripts</a></li>
  <li><a href="#run-the-ios-app">Run the iOS App</a></li>
  <li><a href="#run-the-android-app">Run the Android App</a></li>
  <li><a href="#run-the-electron-app">Run the Electron App</a></li>
  <li><a href="#part-1-conclusion">Part 2 Conclusion</a></li>
</ul>

<hr />

<h3 id="install-native-required-packages">Install Native Required Packages</h3>

<ul>
  <li>
    <p>In order to build Android, iOS, or Electron applications on specific devices, it is necessary to install the necessary capacitor packages first. So run the following commands:</p>

    <pre><code class="language-bash"> npm install --save @capacitor/android
 npm install --save @capacitor/ios
 npm install --save @capacitor-community/electron
</code></pre>
  </li>
  <li>
    <p>Integrate the various platforms into the application.</p>

    <pre><code class="language-bash"> npx cap add android
 npx cap add ios
 npx cap add @capacitor-community/electron
</code></pre>
  </li>
</ul>

<h3 id="update-config-file">Update Config file</h3>

<p>The <code>capacitor.config.ts</code> file specifies parameters that the plugin needs, such as database location, database encryption, and the use of biometric authentication for access security. Such settings may be platform specific.</p>

<ul>
  <li>
    <p>Please modify the <code>capacitor.config.ts</code> file as below :</p>

    <pre><code class="language-ts"> import { CapacitorConfig } from '@capacitor/cli';

 const config: CapacitorConfig = {
 appId: 'YOUR_APP_ID',
 appName: 'YOUR_APP_NAME',
 webDir: 'www',
 loggingBehavior: 'debug',
 server: {
     androidScheme: "http"
 },
 plugins: {
     CapacitorSQLite: {
     iosDatabaseLocation: 'Library/CapacitorDatabase',
     iosIsEncryption: false,
     iosKeychainPrefix: 'YOUR_APP_NAME',
     iosBiometric: {
         biometricAuth: false,
         biometricTitle : "Biometric login for capacitor sqlite"
     },
     androidIsEncryption: false,
     androidBiometric: {
         biometricAuth : false,
         biometricTitle : "Biometric login for capacitor sqlite",
         biometricSubTitle : "Log in using your biometric"
     },
     electronIsEncryption: false,
     electronWindowsLocation: "C:\\ProgramData\\CapacitorDatabases",
     electronMacLocation: "/Users/YOUR_NAME/CapacitorDatabases",
     electronLinuxLocation: "Databases"
     }
 }
 };
 export default config;
</code></pre>
  </li>
</ul>

<h3 id="update-packagejson-scripts">Update Package.json Scripts</h3>

<ul>
  <li>
    <p>First install a new package to remove the sql.js wasm file to reduce the native package size</p>

    <pre><code class="language-bash"> npm install --save-dev rimraf
</code></pre>
  </li>
  <li>
    <p>Open the <code>package.json</code> file and replace the scripts section with:</p>

    <pre><code class="language-json"> "scripts": {
     "ng": "ng",
     "start": "npm run copy:sql:wasm &amp;&amp; ng serve",
     "build:native": "npm run remove:sql:wasm &amp;&amp; ng build",
     "watch": "npm run copy:sql:wasm &amp;&amp; ng build --watch --configuration development",
     "test": "ng test",
     "lint": "ng lint",
     "ionic:serve:before": "npm run copy:sql:wasm",
     "copy:sql:wasm": "copyfiles -u 3 node_modules/sql.js/dist/sql-wasm.wasm src/assets",
     "remove:sql:wasm": "rimraf src/assets/sql-wasm.wasm",
     "ionic:ios": "npm run remove:sql:wasm &amp;&amp; ionic capacitor build ios",
     "ionic:android": "npm run remove:sql:wasm &amp;&amp; ionic capacitor build android",
     "electron:install": "cd electron &amp;&amp; npm install &amp;&amp; cd ..",
     "electron:prepare": "npm run remove:sql:wasm &amp;&amp; ng build &amp;&amp; npx cap sync @capacitor-community/electron &amp;&amp; npx cap copy @capacitor-community/electron",
     "electron:start": "npm run electron:prepare &amp;&amp; cd electron &amp;&amp; npm run electron:start"
 },
</code></pre>
  </li>
</ul>

<h3 id="run-the-ios-app">Run the iOS App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> npm run ionic:ios
</code></pre>
  </li>
  <li>
    <p>In Xcode wait for indexed file to complete, clean the project and run the app. You will get the following screen</p>
  </li>
</ul>

<div align="center"><br /><img src="/images/Part2-iOS-Ionic7-Angular-SQLite-Managing-Users.png" width="50%" /></div>
<p><br /></p>

<h3 id="run-the-android-app">Run the Android App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> npm run ionic:android
</code></pre>
  </li>
  <li>
    <p>In Android Studio</p>

    <ul>
      <li>go to the menu Android/Preferences/Build, Execution, Deployment/Build Tools/Gradle and then select the gradle JDK <code>17 Oracle OpenJDK Version 17.0.7</code>. Then press <code>Apply</code> and <code>OK</code>.</li>
      <li>go to File/Sync Project With Gradle Files.</li>
      <li>go to Build/Clean Project.</li>
      <li>select your Emulator or Physical Device.</li>
      <li>run the app</li>
    </ul>
  </li>
  <li>
    <p>Screenshot of the screen:</p>
  </li>
</ul>

<div align="center"><br /><img src="/images/Part2-Android-Ionic7-Angular-SQLite-Managing-Users.png" width="50%" /></div>
<p><br /></p>

<h3 id="run-the-electron-app">Run the Electron App</h3>

<ul>
  <li>
    <p>Run the following command:</p>

    <pre><code class="language-bash"> cd electron
</code></pre>
  </li>
  <li>
    <p>Open the <code>package.json</code> file and replace the scripts:, dependencies:, devDependencies: sections with:</p>

    <pre><code class="language-json"> "scripts": {
     "build": "tsc &amp;&amp; electron-rebuild",
     "electron:start-live": "node ./live-runner.js",
     "electron:start": "npm run build &amp;&amp;  electron --inspect=5858 ./",
     "electron:pack": "npm run build &amp;&amp; electron-builder build --dir -c ./electron-builder.config.json",
     "electron:make": "npm run build &amp;&amp; electron-builder build -c ./electron-builder.config.json -p always"
 },
 "dependencies": {
     "@capacitor-community/electron": "^4.1.2",
     "@capacitor-community/sqlite": "^5.0.7",
     "better-sqlite3-multiple-ciphers": "^8.4.0",
     "chokidar": "~3.5.3",
     "crypto": "^1.0.1",
     "crypto-js": "^4.1.1",
     "electron-is-dev": "~2.0.0",
     "electron-json-storage": "^4.6.0",
     "electron-serve": "~1.1.0",
     "electron-unhandled": "~4.0.1",
     "electron-updater": "~5.0.1",
     "electron-window-state": "~5.0.3",
     "jszip": "^3.10.1",
     "node-fetch": "2.6.7"
 },
 "devDependencies": {
     "@types/better-sqlite3": "^7.6.4",
     "@types/crypto-js": "^4.1.1",
     "@types/electron-json-storage": "^4.5.0",
     "electron": "^25.2.0",
     "electron-builder": "^24.6.3",
     "electron-rebuild": "^3.2.9",
     "rimraf": "^5.0.1",
     "typescript": "~4.3.5"
 },

</code></pre>
  </li>
  <li>
    <p>Then run the following commands:</p>

    <pre><code class="language-bash"> npm install
 cd ..
 npm run electron:start
</code></pre>
  </li>
  <li>
    <p>Screenshot of the screen</p>
  </li>
</ul>

<div align="center"><br /><img src="/images/Part2-Electron-Ionic7-Angular-SQLite-Managing-Users.png" width="50%" /></div>
<p><br /></p>

<h3 id="part-2-conclusion">Part 2 Conclusion</h3>

<p>We have completed the Part 2 - Native and Electron applications of the Ionic 7 SQLite Database CRUD App Example Tutorial using Angular and @capacitor-community/sqlite.</p>

<p>We have learned to adapt the <code>capacitor.config.ts</code>file and the modify the scripts: section of the <code>package.json</code>file for native apps</p>

<p>We learned how to build and run the application for each native platforms.</p>

<p>Enjoy your development from there.</p>]]></content><author><name>Quéau Jean Pierre</name></author><category term="Other" /><summary type="html"><![CDATA[]]></summary></entry></feed>