Logicoya

useRouter

useRouterとは

useRouter() はNext.jsでルーティングコンポーネントで、URLパス、クエリパラメータなどのルーティング情報を処理できます。

useRouterの基本

インポート

next/navigation から「useRouter」をインポートします。

import { useRouter } from 'next/navigation';
  • 旧バージョンでは「next/router」

useRouter()

useRouter() でオブジェクトを生成します。

const router = useRouter();

パスの取得

現在のパス

const currentPath = router.pathname;

クエリパラメータ

const queryParam = router.query.paramName;

リダイレクト

userRouterのリダイレクトにはpush() と replace() があり、基本動作は同じですが、キャッシュの違いがあります。

push()

push() の場合は、リダイレクト後にブラウザにキャッシュされ【Back】で戻ることができます。

router.push(URI);

replace()

replace() の場合は、リダイレクト後にブラウザの【Back】で戻ることができません。

router.replace(URI);

ユーザ登録処理

インポート

UserServiceとnext/navigationコンポーネントをインポートします。

app/auth/regist/page.tsx
"use client";

import { useState } from 'react';
import { RegistUser } from '@/app/services/UserService';
import { useRouter } from 'next/navigation';

...

ユーザ登録実行

RegistUser でユーザ登録を非同期通信で実行します。

onClickイベント

【Sign up】ボタンの onClickイベントハンドラーに regist を設定します。

function RegistPage() {
    ...

    return (
        <div className="mx-auto w-1/3">
            ...
            <div>
                <button
                    className="py-2 px-4 my-3 w-full 
                    bg-black hover:bg-gray-800 
                    focus:shadow-outline focus:outline-none 
                    text-white 
                    rounded-lg"
                    onClick={regist}
                >Sign up</button>

                ...
            </div>
        </div>
   ...
}

regist() メソッド定義

regist() を非同期処理で追加します。

app/auth/regist/page.tsx
function RegistPage() {
    ...
    const regist = async () => {

    }
   ...

}
コーディングのコツ

メソッドが未定義のときは、クイックフィックスでコードアシスタントすると効率的です。

クイックフィックス
メソッド追加

TypeScriptの型推測で入力してくれます。

コードアシスタント
    function regist(event: MouseEvent<HTMLButtonElement, MouseEvent>): void {
        throw new Error("Function not implemented.");
    }

ユーザ登録処理

ユーザ登録処理を実行し、ユーザデータを取得します。

app/auth/regist/page.tsx
function RegistPage() {
    ...

    const regist = async () => {
        //ユーザ登録処理
        const result = await registUser({ name, email, password });
        const user = result?.user;
    }
   ...

}

リダイレクト

useRouter追加

コンポーネントのトップにuseRouter を追加します。

app/auth/regist/page.tsx
function RegistPage() {
    const router = useRouter();
    ...
}
コーディングのコツ

Next.js 13以降の userRouterは、next/navigationが推奨となりました。「userRouter()」を入力したら、クイックフィックスでnext/navigationを選択しましょう。

トップページにリダイレクト

ユーザ登録の結果がエラーの時はコンソールにエラー表示、成功した場合はトップページにリダイレクトします。

app/auth/regist/page.tsx
function RegistPage() {
    const router = useRouter();
    ...

    const regist = async () => {
        const result = await registUser({ name, email, password });
        if (result.error) {
            // エラー
            console.log(result.error);
        } else {
            const user = result?.user;
            if (user) {
                // トップページにリダイレクト
                router.replace('/');
            }
        }
    }
   ...

}

エラーハンドリング

エラーメッセージコンポーネント

「app/components/FormError.tsx」を作成し、エラーメッセージコンポーネントを作成します。

app/components/FormError.tsx
import { FaExclamationCircle } from "react-icons/fa";

interface FormErrorProps {
    message: string
}

const FormError = ({ message }: FormErrorProps) => {
    if (!message) return;
    return (
        <div className='p-2 flex text-red-700 bg-red-100 rounded-lg'>
            <FaExclamationCircle className='mt-1 mx-2' />
            <div>{message}</div>
        </div>
    );
}

export default FormError;

エラーメッセージ定義

エラーメッセージの変数「error」を定義します。初期値は RegistErrorで「name」「email」「password」のstring型とします。

app/auth/regist/page.tsx
...
// 型定義
interface RegistError {
    name: string;
    email: string;
    password: string;
}

function RegistPage() {
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    // 変数 error 追加
    const [error, setError] = useState<RegistError>({ name: '', email: '', password: '' });
   ...

}

エラーハンドリング

ユーザ登録エラーのとき、setError() でエラーメッセージを設定します。

app/auth/regist/page.tsx
    const regist = async () => {
        const result = await registUser({ name, email, password });
        const user = result?.user;
        if (result.error) {
            // エラーメッセージを設定
            setError(result.error);
        } else {
            router.push('/');
        }
    }

エラーメッセージ表示

FormErrorコンポーネントでエラーメッセージを表示します。

app/auth/regist/page.tsx
import { FaUser } from "react-icons/fa";
import Link from 'next/link';
import Input from '@/app/components/Input';
// インポート
import FormError from '@/app/components/FormError';
...

function RegistPage() {
    ...

    return (
        <div className="mx-auto w-1/3">
            ...

            <div>
                <Input 
                type="text" 
                value={name} 
                placeholder="Your Name" 
                onChange={setName} />
                <FormError message={error.name} />

                <Input 
                type="email" 
                value={email} 
                placeholder="Email" 
                onChange={setEmail} />
                <FormError message={error.email} />

                <Input 
                type="password" 
                value={password} 
                placeholder="Password" 
                onChange={setPassword} />
                <FormError message={error.password} />
            </div>
            ...
        </div>
    );
}

ユーザ登録確認

ユーザ登録フォームでデータを送信します。

ユーザ登録成功

ユーザ登録に成功するとトップページにリダイレクトします。usersテーブルに登録されたか確認してみましょう。

ユーザ登録エラー

ユーザ登録エラーの場合、エラーメッセージが表示されるか確認します。