家計簿アプリを作る #14:登録・編集後の月フィルタ維持

家計簿アプリ作成シリーズの第14回です。今回は収支の登録・編集後に元の月フィルタ状態に戻る処理を実装します。

課題

前回までの実装では、収支を登録・編集すると / にリダイレクトされるため、月フィルタ(?month=2026-06)がリセットされてしまいます。登録・編集完了後も選択中の月に戻るようにします。

実装方針

月情報を以下の流れで引き継ぎます。

  1. 一覧ページの「登録」「編集」リンクに ?from=2026-06 を付ける
  2. 登録・編集ページの loadfrom を受け取り、<input type="hidden"> でフォームに埋め込む
  3. action で hidden input の値を受け取り、リダイレクト先に ?month=2026-06 を付ける

Step 1:一覧ページのリンクに月情報を付ける

<!-- 登録リンク -->
<a href={`/transactions/new?from=${data.selectedMonth ?? ''}`}>登録</a>

<!-- 編集リンク -->
<a href={`/transactions/${transaction.id}/edit?from=${data.selectedMonth ?? ''}`}>編集</a>

data.selectedMonthnull(月未選択)のときは空文字を渡します。

Step 2:登録・編集ページの load で月を受け取る

export const load: PageServerLoad = async ({ locals, url }) => {
  const selectedMonth = url.searchParams.get('from');
  return { selectedMonth };
};

Step 3:<input type="hidden"> でフォームに埋め込む

<input type="hidden" name="month" value={data.selectedMonth} />

Step 4:action でリダイレクト先に月を付ける

const selectedMonth = formData.get('month');

redirect(303, selectedMonth ? `/?month=${selectedMonth}` : '/');

selectedMonth が空文字や null のときは / にリダイレクトします。

ハマりポイント:クエリパラメータ名の typo

loadurl.searchParams.get('form') と書いてしまい、null が返り続けるという問題が起きました。正しくは 'from' です。

// ❌ typo
const selectedMonth = url.searchParams.get('form');

// ✅ 正しい
const selectedMonth = url.searchParams.get('from');

また、リダイレクト先のテンプレートリテラルで $ を書き忘れるミスもありました。

// ❌ $ が抜けている
redirect(303, `/?month={selectedMonth}`);

// ✅ 正しい
redirect(303, `/?month=${selectedMonth}`);

まとめ

ポイント 内容
月情報の引き継ぎ リンクの ?from=load → hidden input → action の流れで渡す
月未選択時 selectedMonth ?? '' で空文字にして / にフォールバック
typo に注意 'from''form'${selectedMonth}{selectedMonth} を混同しやすい

次回はUI全体の見直しを行います。

← トップページに戻る