How to trigger server function for SSR when transitioning routes?
Is there any way to achieve a new SSR call to the backend for each route I
navigate()
with useNavigate()
within a [slug] pattern?
I have a createAsync()
in [slug].tsx that is supposed to get some data from the backend based on the route I get to, but it triggers only with a full refresh of the tab in the browser or fisrt page load, if I try to navigate()
from inside the app the createAsync()
function is not called anymore, it's a "use server" declared function, with a cache()
wrapper, just like the examples on docs.
Ideally I wouldn't use <A>
components and stick to useNavigate()
but I'm open to anything would make this work.
Maybe this is the correct behavior of my setup but I couldn't find anything related to my use-case in the docs4 Replies
Could share some code?
How do you get the slug param etc.
Sure:
/path/to/[slug].tsx
This is the page itself
NavigatorItem.tsx
This is one of the navigation components that is mounted right inside the <Router>
but not inside the [slug].tsx
page
app.tsx
The Root:
The problem is that getInitialProps()
gets triggered only on full refresh or first load, if I click on <NavigatorItem />
the route changes but the content isn't fetched for the new slugYou shouldn't use
useParams
in a server function. Those hooks are meant to be used inside components.
You may pass the the slug instead as a param to the server function like this:
And instead of using a div
with onClick you may prefer to use an anchor tag a
or A
so hovering them will trigger the preload function to fetch the new data before the user click. This way you have almost immediate page transitions as the data is probably already there when the user clicks.Thanks for the help, indeed using the slug as an argument to getInitialProps solved the problem, not everything works as expected!
I've been reading about not using the use* functions on the server but damn, the docs are so much empty...
Kudos! 🙏