beforeLoad -> loader question
Hi all.
I've been enjoying the Router but I have a quick question.
In beforeLoad I make a check if context has a key value pair and I fetch the data and store it to the context.
In the next step I use the loader to check the value from the beforeLoad context save to decide if I'm redirecting the user to a top level page ( change-password ).
Is this the preferred / correct way of doing this?
Since I can't redirect in the beforeLoad since the context would not be stored if I redirect there.
Any comments on this approach? Is there a better way of doing it? Is there something like an additional pipe like afterBeforeLoad?
Cheers!
3 Replies
genetic-orange•5mo ago
you can use
directly in your beforeLoad, dont need to wait doing that in loader
fascinating-indigo•5mo ago
It's also worth just understanding what the purpose of both beforeLoad and loader are.
beforeLoad
is middleware, it is for doing something that must happen in a parent route before going deeper into the route tree, and subsequent routes beforeLoads do not run until this routes beforeLoad is run - meaning that you can inject data, or redirect before even getting to the route.
loader
is for data fetching and anything that needs to happen before the route component is mounted. i.e, it is the thing that you should run, when you want to do something just before the component itself is mounted.
In your case, dohomi's suggestion would make the most sense, even though you could run your redirect inside the loader. the reason is, you do not want to start making API requests for specific routes, if you are just going to redirect the user to another page.correct-apricotOP•5mo ago
yeah the thing is that when the beforeLoad runs and the router context doesn't have the pair I want to make sure that the context gets updated with the fetch I make. And as I've looked through the docs and how I understand it I have to
return
the new context object in the beforeLoad for it to actually get merged into the context object - therefore I can't redirect because it wont get stored to the context.
That's why I load it in the beforeLoad and I do the check in the loader.
So I know that the context gets updated and the loader can then redirect if a key value in the context is true for an example.
But reading both your comments I guess I understood it correctly 😄
Cheers for the comments!