Open Gregory-Gerard opened 3 weeks ago
I have the same problem !
Looks like I have the same problem, but with router.get
and router.visit
in useEffect too. In my case I needed to redirect user to /login
page from /
initially if user is not logged in. So I used `router.get('/login') with useEffect. Probably better to move this logic to backend instead. But still, I were expect router to work in useEffect even initially.
Version:
@inertiajs/react
version: 1.1.0Describe the problem:
Implementing lazy loading with Inertia::lazy in Laravel works well for asynchronous data fetching and improves Time To First Byte (TTFB). Using router.visit navigates the application effectively. However, an issue arises when reloading the page: the data fetch initiates correctly but the data itself fails to update in the UI.
Steps to reproduce:
When calling
router.reload
in auseEffect
, we notice that the data is not updated correctly when reloading page using the browser.Unfortunately, this issue has already been raised, for example: https://github.com/inertiajs/inertia/issues/1547
The
setTimeout(..., 0)
solution still works but something seems off about it.Debug:
I've tried to do a little debugging and apply some logs to understand what's going on. When the Inertia application is created for the first time, the
router.init
method is launched, followed byrouter.handleInitialPageVisit
. We can then notice that thesetPage
method is called, in which the element of interest is this one: https://github.com/inertiajs/inertia/blob/683155c8639aef8dc812c3fab4cdb5e2a35eccde/packages/core/src/router.ts#L469So I started logging this condition, and indeed, on the first load the
visitId
changes because therouter.reload
is called before therouter.handleInitialPageVisit
. So when we receive therouter.reload
result, because of this condition, the result is ignored because thevisitId
has been updated byrouter.handleInitialPageVisit
.A possible solution?
I've never contributed to Inertia, so certainly this solution may have edge cases, but having a bit of fun with the sources I noticed that
setPage
can take avisitId
as a parameter to avoid regenerating it.So, if I detect that a
visitId
has already been initialized before thehandleInitialPageVisit
, I can simply reuse it to avoid regenerating it and ignore therouter.reload
result.View source: https://github.com/inertiajs/inertia/blob/683155c8639aef8dc812c3fab4cdb5e2a35eccde/packages/core/src/router.ts#L87
When using this patch, here is the result: And the UI updates well, whether following a
router.visit
or a browser reload.If this solution is suitable, I can make a PR with test cases if necessary. In the meantime, I'm keeping the
setTimeout(..., 0)
which works for the moment. Also, many thanks for this library.