1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

next.js 画面をリロードさせる

Last updated at Posted at 2022-07-18

結論

next.jsで画面をリロードさせるのは、以下のコードで出来ます。

router.reload()

トップページに移動させたい場合は、router.push("/")と書きます。

全体のコード

全体のコードとしては、以下のような感じです。ログインボタンを押して、ログインが成功した時、ログアウトボタンを押した時に画面をリロードさせるという処理です。なお、amplifyとcognitoを使っています。
5行目のimport Router, { useRouter } from 'next/router'

8行目のconst router = useRouter()
が必要な行です。

import React, { useState } from "react"
import type { NextPage } from 'next'
import Amplify, { Auth } from 'aws-amplify'
import * as cognito from "./api/cognito"
import Router, { useRouter } from 'next/router'

const Sign_in: NextPage = () => {
  const router = useRouter()

  // ログイン時
  const onLogin = async (e:any) => {
    try {
      // ログインを実行する
      const user = await cognito.login(userId, password);
      console.log("ログイン成功 : ")
      router.reload() // リロードしないと、認証の状態が変わらないため
    } catch (e:any) {
      console.log("ログイン失敗")
    }
  };

  // ログアウト時
  const onLogout = async (e:any) => {
    try {
      await Auth.signOut();
    } catch (error) {
      console.log('Error Logging Out', error);
    }
    router.reload() // リロードしないと、認証の状態が変わらないため
  };

  return (
    <div>
           〜〜省略〜〜
    </div>
  );
}

export default Sign_in;

動作環境

$ sw_vers
ProductName:	macOS
ProductVersion:	11.6.5
BuildVersion:	20G527

$ node -v
v16.13.0

$ npm list -g
├── next@12.2.2
├── react@18.2.0
├── typescript@4.7.4

めでたし、めでたし。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?