0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactのlocalstrage使用

Posted at

Reactのローカルストレージについての記事です
メモ帳アプリで使用した場合について書いてみました。

ローカルストレージとは

localStorage(ローカルストレージ)は、ウェブブラウザが提供する機能の1つで、ユーザーのデバイスにデータを保存するために使います。これにより、データをブラウザに永続的に保存でき、ユーザーがページをリロードしたりブラウザを閉じたりしても、データが失われません。

使用前準備

仕様する前に簡単な準備を行います。
データの保存をするuseStateと,副作用を行うuseEffectを設定しました。

import { useState, useEffect } from "react";

export default function App() {
  const [notes, setNotes] = useState([]);
  const [text, setText] = useState("");

ローカルストレージからデータを取得

コンポーネントが初めてレンダリングされたとき(依存配列が空なので一度だけ実行)
ローカルストレージから保存された notes を取得します。


useEffect(() => {
  const storedNotes = JSON.parse(localStorage.getItem("notes")) || [];
  setNotes(storedNotes);
}, []);

詳しい内容


localStorage.getItem("notes"):

//ローカルストレージに保存されたキー "notes" に関連付けられた値(文字列)を取得します。

JSON.parse(...):

//上記で取得した文字列データを、元のオブジェクトまたは配列に変換します。

|| []:

//万が一 "notes" にデータが存在しない場合、null が返されます。そのためデフォルト値として空の配列 [] を設定しています。

データをローカルストレージに保存

notes が更新されるたびに、新しいデータをローカルストレージに保存します。

  useEffect(() => {
    localStorage.setItem("notes", JSON.stringify(notes));
  }, [notes]);

詳しい内容

localStorage.setItem("notes", JSON.stringify(notes));

//使いかたはこうです

localStorage.setItem(key, value):

//localStorage は、ブラウザのローカルストレージにデータを保存するためのオブジェクトです。

//key: データにアクセスする際の名前(ここでは "notes")。

//value: 保存するデータ(文字列形式でなければならない)。

}, [notes]);

//配列内の値(ここでは notes)が更新されるたびに、useEffect 内の処理が再度実行されます。

//もし依存配列が空([])の場合は、コンポーネントの初回レンダリング時にのみ実行されます。

//この場合、notes が追加・削除などで変化するたびにローカルストレージに保存処理が実行されます。

その他使用関数

メモの追加機能

入力された内容が空白でない場合、現在のメモリスト(notes)に新しいメモ(text)を追加します。

setNotes([...notes, text]); は現在の配列を展開し、新しい項目を末尾に追加する構文です。

const addNote = () => {
  if (text.trim() === "") return;
  setNotes([...notes, text]);
  setText("");
};

削除機能

filter を使って、指定されたインデックスのメモだけを除外した新しい配列を作成します。

const deleteNote = (index) => {
  setNotes(notes.filter((_, i) => i !== index));
};

JSX(JavaScript XML)

 return (
    <div className="min-h-screen bg-gray-100 flex flex-col items-center p-6">
      <h1 className="text-2xl font-bold mb-4">メモ帳アプリ</h1>
      <div className="bg-white shadow-md rounded-lg p-4 w-full max-w-md">
        <textarea
          className="w-full p-2 border rounded resize-none focus:outline-none"
          rows="3"
          placeholder="メモを入力..."
          value={text}
          onChange={(e) => setText(e.target.value)}
        />
        <button
          className="w-full bg-blue-500 text-white py-2 mt-2 rounded hover:bg-blue-600"
          onClick={addNote}
        >
          メモを追加
        </button>
      </div>

      <ul className="mt-4 w-full max-w-md">
        {notes.map((note, index) => (
          <li
            key={index}
            className="bg-white shadow p-3 rounded mt-2 flex justify-between items-center"
          >
            <span>{note}</span>
            <button
              className="text-red-500 hover:text-red-700"
              onClick={() => deleteNote(index)}
            >
              削除
            </button>
          </li>
        ))}
      </ul>
    </div>
  );

実際のコード

詳しい内容はこちらへ

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?