IndexedDB の初心者ガイド

DDD
リリース: 2024-09-26 08:21:42
オリジナル
377 人が閲覧しました

A Beginner

Web アプリでのクライアント側ストレージの使用に関するチュートリアル

最新の Web アプリケーション、特にプログレッシブ Web アプリ (PWA) を構築する場合、データをオフラインで保存する方法を確保することが重要です。 IndexedDB は、ユーザーがオフラインの場合でも、Web アプリがデータを保存および取得できるようにする強力なクライアント側データベースです。このガイドでは、IndexedDB の基本を説明し、Web アプリ内でデータを作成、読み取り、更新、削除 (CRUD 操作) する方法を示します。

IndexedDB とは何ですか?

IndexedDB は、ファイルや BLOB などの大量の構造化データをクライアント側でストレージするための低レベル API です。 localStorage とは異なり、IndexedDB では文字列だけでなく複雑なデータ型を保存できます。非同期のトランザクション データベース モデルを使用しているため、大規模なデータセットやオフライン データ同期を処理する必要があるアプリケーションにとって強力です。

IndexedDB を使用する理由

  • オフライン機能: プログレッシブ Web アプリ (PWA) およびオフラインファーストのアプリケーションに最適です。
  • ストレージ容量: IndexedDB は、localStorage (約 5 ~ 10 MB に制限されています) と比較して、はるかに多くのデータを保存できます。
  • 柔軟性: 配列、オブジェクト、BLOB などの複雑なオブジェクトを保存します。
  • 非同期: 操作は UI スレッドをブロックしません。つまり、アプリは応答性を維持します。

はじめに: IndexedDB のセットアップ

IndexedDB を使用するための中心的な手順を見てみましょう。以下について説明します:

  • データベースを作成または開く
  • オブジェクト ストア (テーブル) の作成
  • データの追加
  • データの読み取り
  • データを更新中
  • データの削除

ステップ 1: データベースを開く

IndexedDB と対話するには、まずデータベースへの接続を開く必要があります。データベースが存在しない場合は作成されます。

const request = indexedDB.open('MyCustomersDatabase', 1);

request.onerror = (event) => {
    console.error('Database error:', event.target.errorCode);
};

request.onsuccess = (event) => {
    const db = event.target.result;
    console.log('Database opened successfully', db);
};

request.onupgradeneeded = (event) => {
    const db = event.target.result;
    if (!db.objectStoreNames.contains('customers')) {
        const objectStore = db.createObjectStore('customers', { keyPath: 'id' });
        objectStore.createIndex('name', 'name', { unique: false });
        objectStore.createIndex('email', 'email', { unique: true });
        console.log('Object store created.');
    }
};
ログイン後にコピー

何が起こっているかは次のとおりです:

  • IndexedDB.open はデータベースを開くか作成します。
  • onerror はデータベースを開くときに発生するエラーを処理します。
  • onsuccess は、データベース接続が正常に開かれたときにトリガーされます。
  • onupgradeneeded は、データベースをアップグレードする必要がある場合 (たとえば、初めてデータベースを開いた場合やバージョンが変更された場合) に起動されます。ここでオブジェクト ストアを定義します (SQL のテーブルと考えてください)。

ステップ 2: IndexedDB へのデータの追加

データベースとオブジェクト ストアのセットアップが完了したので、それにデータを追加しましょう。

const addCustomer = (db, customer) => {
    const transaction = db.transaction(['customers'], 'readwrite');
    const objectStore = transaction.objectStore('customers');
    const request = objectStore.add(customer);

    request.onsuccess = () => {
        console.log('Customer added:', customer);
    };

    request.onerror = (event) => {
        console.error('Error adding customer:', event.target.errorCode);
    };
}

const customer = { id: 1, name: 'John Doe', email: 'john@example.com' };

request.onsuccess = (event) => {
    const db = event.target.result;
    addCustomer(db, customer);
};
ログイン後にコピー

何が起こっているかは次のとおりです:

  • 変更を許可するために「読み取り/書き込み」アクセス権を持つトランザクションを作成します。
  • add() メソッドは、オブジェクト ストアにデータを挿入するために使用されます。
  • 成功イベントとエラー イベントをリッスンして、データが正常に追加されたかどうかを確認します。

ステップ 3: IndexedDB からのデータの読み取り

IndexedDB からのデータの読み取りも簡単です。 get() メソッドを使用して、追加したばかりの顧客を取得しましょう。

const getCustomer = (db, id) => {
    const transaction = db.transaction(['customers'], 'readonly');
    const objectStore = transaction.objectStore('customers');
    const request = objectStore.get(id);

    request.onsuccess = (event) => {
        const customer = event.target.result;
        if (customer) {
            console.log('Customer found:', customer);
        } else {
            console.log('Customer not found.');
        }
    };

    request.onerror = (event) => {
        console.error('Error fetching customer:', event.target.errorCode);
    };
}

request.onsuccess = (event) => {
    const db = event.target.result;
    getCustomer(db, 1); // Fetch customer with ID 1
};
ログイン後にコピー

ステップ 4: IndexedDB のデータを更新する

既存のレコードを更新するには、put() メソッドを使用できます。このメソッドは add() と同様に機能しますが、キーがすでに存在する場合はレコードを置き換えます。

const updateCustomer = (db, customer) => {
    const transaction = db.transaction(['customers'], 'readwrite');
    const objectStore = transaction.objectStore('customers');
    const request = objectStore.put(customer);

    request.onsuccess = () => {
        console.log('Customer updated:', customer);
    };

    request.onerror = (event) => {
        console.error('Error updating customer:', event.target.errorCode);
    };
}

const updatedCustomer = { id: 1, name: 'Jane Doe', email: 'jane@example.com' };

request.onsuccess = (event) => {
    const db = event.target.result;
    updateCustomer(db, updatedCustomer);
};
ログイン後にコピー

ステップ 5: IndexedDB からのデータの削除

最後に、レコードを削除するには、delete() メソッドを使用します。

const deleteCustomer = (db, id) => {
    const transaction = db.transaction(['customers'], 'readwrite');
    const objectStore = transaction.objectStore('customers');
    const request = objectStore.delete(id);

    request.onsuccess = () => {
        console.log('Customer deleted.');
    };

    request.onerror = (event) => {
        console.error('Error deleting customer:', event.target.errorCode);
    };
}

request.onsuccess = (event) => {
    const db = event.target.result;
    deleteCustomer(db, 1); // Delete customer with ID 1
};
ログイン後にコピー

結論

IndexedDB は、特にオフラインファーストの Web アプリにおいて、クライアント側のデータ ストレージを処理するための堅牢なソリューションです。このガイドに従うことで、次の方法を学びました:

  • データベースを開いて作成します
  • オブジェクトストアを作成する
  • データの追加、読み取り、更新、削除

IndexedDB を使用すると、データをローカルに保存し、インターネット接続がなくても動作する、より復元力の高い Web アプリケーションを構築できます。

参考文献:

  1. MDN Web ドキュメント - IndexedDB API

    IndexedDB の仕組み、その API メソッド、ユースケースに関する包括的なガイド。

    MDN IndexedDB ガイド

  2. Google Developers - IndexedDB

    オフライン対応 Web アプリを構築するためのベスト プラクティスと IndexedDB の使用法を説明する詳細な記事。

    Google 開発者 - IndexedDB

  3. W3C インデックス付きデータベース API

    IndexedDB の技術的な実装と構造を概説する W3C の公式仕様。

    W3C IndexedDB 仕様

このチュートリアルを超えて IndexedDB についてさらに詳しく知りたい場合は、これらのリソースがさらなる詳細とコンテキストを提供します!

コーディングを楽しんでください!

以上がIndexedDB の初心者ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!