brgndy
brgndy

Reputation: 97

How do I refresh the page in next.js 14 app router?

Currently using next.js 14 app router.

Modal window on the client-side (the page is the "/" page.)

When logging in is completed. I would like to close the opened login modal window by refreshing the page.

Currently, the router.refresh() method is used using useRouter, but the refresh itself does not work.

What's the problem? I searched and found useRouter.

 import { useRouter } from 'next/router';

It says to use router.reload() after importing like this, but if you do this, the import itself will not work at all.

How can I refresh the page after receiving data?

- my code (use client)

  const apiCallHandler = async () => {

    const res = await fetch(fetch infos);

    const data = await res.json();

    if (success) {

      await asyncFn();

      router.refresh(); // it not works

    }
  };

I'm currently using window.location.reload() as a temporary measure, but I'm leaving a post because I don't think this is the normal method.

Upvotes: 2

Views: 7010

Answers (2)

Bharti Sharma
Bharti Sharma

Reputation: 363

You need to use next/navigation to import useRouter in NextJS14 and from here you can reload your page using refresh method. Please check below code:-

import { useRouter } from 'next/navigation';
const router = useRouter();
router.refresh();

Upvotes: 4

This works for me!

Make the route that needs a refresh an optional route parameter like below

[[...slug]]

refresh the page by navigating to the same route with a different refreshId

import { useRouter } from 'next/navigation';

router.push(``/home?refreshId=${new Date().getTime()}`)

Upvotes: 0

Related Questions