0Pricing
Electron Desktop App Development · レッスン

ローカルストレージとIndexedDB

Electronアプリ内でクライアント側のデータを永続化するため、`localStorage`や`IndexedDB`などのブラウザー同様のストレージ機構を活用します。

「ローカルストレージとIndexedDB」はCoddyKit上の無料Electron Desktop App Developmentレッスンです。 これはレッスン1/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはElectron Desktop App Development学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Electron Desktop App Developmentコースには全3レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Saving Data in Electron Apps

When building desktop applications with Electron, you often need to save user data or application settings. This is called data persistence.

Unlike web apps that rely on servers, Electron apps can store data directly on the user's computer. This lesson explores two common browser-like storage methods: localStorage and IndexedDB.

Introducing Web Storage API

Electron's renderer processes are essentially web browsers. This means you can use standard browser APIs for data storage, like the Web Storage API.

The Web Storage API provides two main types:

  • localStorage: Stores data with no expiration date.
  • sessionStorage: Stores data only for the duration of the browser session.

We'll focus on localStorage for persistent data.

Understanding localStorage

localStorage allows you to store data as simple key-value pairs. Think of it like a small, local dictionary.

  • Persistence: Data stored in localStorage remains even after the app is closed and reopened.
  • Scope: Data is unique to the origin (your app's domain, usually file:// for Electron).
  • Capacity: Limited to about 5-10 MB per origin.

It's great for small amounts of data like user preferences or simple settings.

Storing Data with localStorage

You can store data in localStorage using the setItem() method. Remember, values are always stored as strings.

Try running this example in your renderer process:

/* This code runs in the Electron renderer process. */

const username = "CoddyKitUser";
localStorage.setItem("userName", username);

const userSettings = {
  theme: "dark",
  notifications: true
};
// Objects need to be converted to JSON strings
localStorage.setItem("appSettings", JSON.stringify(userSettings));

console.log("Data saved to localStorage!");

Retrieving & Removing localStorage Data

To get data back, use getItem(). To delete, use removeItem(). If you stored an object, you'll need to parse it back from JSON.

Run this snippet after the previous one:

/* This code runs in the Electron renderer process. */

const storedUsername = localStorage.getItem("userName");
console.log("Stored Username:", storedUsername);

const storedSettingsString = localStorage.getItem("appSettings");
if (storedSettingsString) {
  const storedSettings = JSON.parse(storedSettingsString);
  console.log("Stored Theme:", storedSettings.theme);
}

// To remove an item:
localStorage.removeItem("userName");
console.log("Username removed.");

// To clear all localStorage for the origin:
// localStorage.clear();

Limitations of localStorage

While easy to use, localStorage has some limitations:

  • Size Limit: Typically 5-10 MB per origin. Not suitable for large datasets.
  • String-Only: All data is stored as strings. Objects and arrays must be manually serialized (e.g., with JSON.stringify()) and deserialized (JSON.parse()).
  • Synchronous: Operations block the main thread, which can cause UI freezes if you're storing/retrieving a lot of data.
  • No Indexing/Querying: You can't directly query data, only access by key.

Introducing IndexedDB

For larger, more structured, and complex data, IndexedDB is a powerful alternative. It's a low-level API for client-side storage of significant amounts of structured data.

  • No Size Limit: Generally limited only by available disk space.
  • Structured Data: Can store JavaScript objects directly, not just strings.
  • Asynchronous: Operations don't block the UI thread, making it suitable for performance-critical apps.

IndexedDB Core Concepts

IndexedDB works with a few key concepts:

  • Databases: You create databases, each with a name and version.
  • Object Stores: Like tables in a relational database, but they store JavaScript objects. Each object store has a key path.
  • Indexes: For fast querying of data within an object store.
  • Transactions: All read and write operations must occur within a transaction, ensuring data integrity.
  • Asynchronous: Operations return IDBRequest objects, which resolve with success or error events (or Promises).

Basic IndexedDB Setup

Setting up IndexedDB involves opening a database and defining object stores. This is usually done in the renderer process.

This example shows how to open a database and create an object store if it doesn't exist:

/* This code runs in the Electron renderer process. */

const request = indexedDB.open("CoddyKitDB", 1); // DB name, version

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

request.onsuccess = (event) => {
  const db = event.target.result;
  console.log("Database opened successfully!");
  // You can now interact with the database (add/get data)
  db.close(); // Close when done if not actively using
};

request.onupgradeneeded = (event) => {
  // This runs if the database didn't exist or version changed
  const db = event.target.result;
  const objectStore = db.createObjectStore("users", { keyPath: "id" });
  console.log("Object store 'users' created.");
  // You can also create indexes here
  objectStore.createIndex("name", "name", { unique: false });
};

Quick Check on Storage

You've learned about localStorage and IndexedDB. Which statement accurately describes a key difference?

Recap: Local & IndexedDB

Great job! You've explored client-side data persistence in Electron:

  • localStorage is simple, synchronous, key-value storage for small, non-critical data.
  • IndexedDB is a powerful, asynchronous, transactional database for large amounts of structured data.

Choosing between them depends on your data's size, structure, and performance needs. Both are crucial for building robust Electron applications that save user data locally.

よくある質問

「ローカルストレージとIndexedDB」レッスンは無料ですか?

はい。「ローカルストレージとIndexedDB」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Electron Desktop App Developmentコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Electron Desktop App Developmentコースには全3レッスンが含まれています。

「ローカルストレージとIndexedDB」で何を学びますか?

Electronアプリ内でクライアント側のデータを永続化するため、`localStorage`や`IndexedDB`などのブラウザー同様のストレージ機構を活用します。 ブラウザで直接実行するハンズオンコードでElectron Desktop App Developmentを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Electron Desktop App Developmentを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのElectron Desktop App Developmentは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/3です。

「ローカルストレージとIndexedDB」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このElectron Desktop App Developmentレッスンでコードを書いて実行できますか?

はい。すべてのElectron Desktop App Developmentレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. ローカルストレージとIndexedDB
  2. ファイルシステムへのアクセス
  3. SQLiteによる組み込みデータベース
← Electron Desktop App Developmentに戻る