I'm trying to understand loaders in [email protected]. How and why is a BrowserRouter doing a DB call? Is this just a contrived example and this is meant to be a client db call for illustration purposes or a there some undocumented server activity taking place here?
https://reactrouter.com/en/main/route/loader
createBrowserRouter([
{
element: <Teams />,
path: "teams",
loader: async () => {
return fakeDb.from("teams").select("*");
},
children: [
{
element: <Team />,
path: ":teamId",
loader: async ({ params }) => {
return fetch(`/api/teams/${params.teamId}.json`);
},
},
],
},
]);
are react router 6.4 loaders called on the server, client or both?
The loaders are called on the client. react-router-dom mainly handles client-side routing. If you are using server-side-rendering then the suggestion from RRD is to use Remix.
I'm trying to understand loaders in react router 6.4+. How and why is a browserRouter doing a DB call?
The "how" is trivial, the loader functions are callback functions that are run prior rendering the routed element. The "why" is so the app can fetch data, validate a user, submit analytics/metrics, etc, when a route is being loaded/accessed. What you want or need to do prior to loading the routed component is really up to your specific use cases.
createBrowserRouter([ { element: <Teams />, path: "teams", loader: async () => { return fakeDb.from("teams").select("*"); }, children: [ { element: <Team />, path: ":teamId", loader: async ({ params }) => { return fetch(`/api/teams/${params.teamId}.json`); }, }, ], }, ]);Is this just a contrived example and this is meant to be a client db call for illustration purposes or a there some undocumented server activity taking place here?
Yes, this is a completely contrived code example for illustration purposes, no undocumented activity. "fakeDb" is some client-side database client that is selecting all the tuples from a "teams" collection and returning it to the Teams component, accessible via the useLoaderData hook. fetch is a standard Javascript API to asynchronously fetch data.
In your example both async functions are making calls to some backend. fakeDb seems to target some sort of SQL server via library/sdk. Fetch is a typical method to call a backend api endpoint (on some server).
The router itself may make calls to the server to get the page content, but it may also be cached in the browser if recently access.
All the code in the snippet is executed in the browser, but as mentioned it does ask a server to do something. But what the server does, that code is somewhere else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With