Mixing server and client components
Answered
Salint posted this in #help-forum
SalintOP
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
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.
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.
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/routerAmerican Crow
share some code
SalintOP
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
SalintOP
"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
SalintOP
the problem was the fetch request being cached
Answer
SalintOP
thanks