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?

【Next.js】GET通信で渡されたパラメータをuseSearchParamsで取得する方法

Last updated at Posted at 2024-12-19

useSearchParamsコンポーネントの導入はシンプル

Next.jsが用意しているクライアントコンポーネント「useSearchParams」は、
GETパラメータの各クエリを取得するためのAPIです。

しかも、導入はとってもカンタンなんです!

パッケージ管理ツールnpmやyarnでインストールしなくても、Next.jsプロジェクトを作成した時からデフォルトで入っています!

クライアントクラスに下記のようにいImportすれば完了です!

app/auth/eventEdit/page.tsx
'use client'

import { useRouter, useSearchParams } from "next/navigation"

画面イメージを見ながらコード解説をしてみる

では、さっそくコードの解説をしていきましょう。

たとえば、次のような一覧画面があるとします。
編集画面.png

この一覧画面のローカルWebサーバでのURLは次の通りです。

URL.png

さて、このURLから①userIdと②eventidをブラウザのコンソールに出力してみましょう。

どう書けばいいかというと、たった2ステップで取得することができます。
【手順】
①useSearchParams関数を定義します。

app/auth/eventEdit/page.tsx
const searchParams = useSearchParams();

②取得するパラメータのクエリ名をgetする。

app/auth/eventEdit/page.tsx
const userId = searchParams.get('userId');
const eventId = searchParams.get('eventId');

はい、これで完了です。

全体のコードはこちら↓(この画面は、これから作りこみ予定です...)

app/auth/eventEdit/page.tsx
'use client'

import { useRouter, useSearchParams } from "next/navigation"
import { useEffect,useState } from "react";
import SelectEvent from "@/app/pages/api/selectEvent";
//import { GETQueryParams } from "@/app/pages/api/urlQueryParameters";

export default function EventEdit(){
    //ルーティングの設定
    const router = useRouter();
    //クライアントコンポーネントフックであるuseSearchParamsを使用する
    const searchParams = useSearchParams();

    //URL Query Paramsからパラメータを取得する
    const userId = searchParams.get('userId');
    const eventId = searchParams.get('eventId');

    console.log("GETパラメータから受け取ったユーザーIDは、" + userId);
    console.log("GETパラメータから受け取ったイベントIDは、" + eventId);

    //ダッシュボードに戻るボタン押下時の処理
    const backToMyDashboard = ()=>{
        router.push("/auth/login/dashboard");
    }
    //状態でイベント情報を管理する
    const [targetEvent,settargetEvent] = useState<any>(null);

    useEffect(()=>{
        const fetchEvent = async ()=>{
            try{
                const event = await SelectEvent(Number(userId),Number(eventId));
                console.log("サーバから取得してきた編集対象イベントは、" + event);
                settargetEvent(event);
            }catch(error){
                console.error("イベントの取得中にエラーが発生しました:", error);
            }
        };
        fetchEvent();                
    },[userId,eventId]);

    console.log("編集対象のイベントは、" + JSON.stringify(targetEvent));

    return (
        <div>
            編集ページ
            <div className="eventEditArea">
                <button className="btn btn-primary">編集する</button>
                <button className="btn btn-accent">クリアする</button>
                <button className="btn btn-secondary" onClick={backToMyDashboard}>戻る</button>
            </div>
        </div>
    )
}

以上です。

0
0
0

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?