Next.js Discord

Discord Forum

Mixing server and client components

Answered
Salint posted this in #help-forum
Open in Discord
To learn next.js, I'm building a dad joke website that pulls data from [icanhazdadjoke API](https://icanhazdadjoke.com/api#fetch-a-dad-joke). I want the component displaying it to be server-side rendered, but I also want a button to refresh the page.

according to the next.js docs, if i want interactivity like onClick i should use client component, so I made a Button class that's a client component, but when I try to refresh the page using useRouter hook which throws me a

NextRouter was not mounted.


What's the proper way of doing this?

P. S: If I can update just the text part by fetching another dad joke after the page has loaded instead of refreshing the page is a plus.
Answered by Salint
the problem was the fetch request being cached
View full answer

21 Replies

American Crow
If you use the App router you have to import the router from next/navigation, while for pages direcotry you import from next/router
American Crow
share some code
one sec
"use client";

import { useRouter } from "next/router";

export default () => {

    const router = useRouter();

    return (
        <button onClick={() => router.reload()}>Another joke</button>
    )
};
ok nvm
so
i was using next/router in app router
i should use next/navigatio
and then change router.reload() to refresh
however
it does absolutely nothing
@American Crow
American Crow
add a console log it's a soft refresh
"use client";

import { useRouter } from "next/navigation";

export default () => {

    const router = useRouter();

    const refresh = () => {
        router.refresh();
        console.log("woah");
    }

    return (
        <button onClick={refresh}>Another joke</button>
    )
};
it prints woah everytime
but
doesnt refresh
ok so i fixed it
the problem was the fetch request being cached
Answer
thanks