T
TanStack3y ago
genetic-orange

🚨 Loader is calling an endpoint too many times

Stackblitz: https://stackblitz.com/edit/stackblitz-starters-fd75no?file=src%2Froutes%2Fapp%2Fsettings%2Fusers%2Froute.tsx In the example you'll find minimal setup for a user list, with ability to filter by username. So what's the problem? 1. Navigate to /app/settings/users 2. Inspect the network tab. 3. Select a value from the Filter by name datalist. 4. See that the jsonplaceholder API is called 6 times. Unsure whether I should be doing something differently, or if this is a bug. All help is highly appreciated 🫶 Thanks for all of your work TanMan @Tanner Linsley and other contributors. This is a beautiful community.
jan144
StackBlitz
tanstack-react-router-demo - StackBlitz
React + TypeScript starter project
3 Replies
genetic-orange
genetic-orange3y ago
I think @Tanner Linsley could fill in any gaps I have. But it looks like the Loader you are using is what is actually a "React Query Lite" version under the hood. If you use the loader on the Route to do your data fetching there rather than using the Loader, I think it would cut down on endpoint calls. Also, strictmode runs everything twice, and so if I recall correctly, in conjunction with React Query or RQ Lite here, it will run it a handful of times because of react querys refetching defaults
genetic-orange
genetic-orangeOP3y ago
Thanks for taking a look! I've been fiddling with this a bunch after I posted originally, but have not found a solution yet. Now I'm using strict: false like so
const users =
useLoaderInstance({
...loaderOptions,
strict: false,
}).data ?? [];
const users =
useLoaderInstance({
...loaderOptions,
strict: false,
}).data ?? [];
` It eliminates the whole route hierarchy from being rerendered, which is nice. So when I type into the "Search by name" box, I don't lose the input focus anymore. However, this does not fix the original problem (i.e. endpoint is still being called 6 times)
genetic-orange
genetic-orangeOP3y ago
Update: I've managed to get this working better 🎉 Fork of the original StackBlitz: https://stackblitz.com/edit/stackblitz-starters-bylnqg?file=src%2Froutes%2Fapp%2Fsettings%2Fusers%2Froute.tsx This is what I've changed from the original StackBlitz: routes/app/settings/users/route.tsx Added maxAge: 0 to the route. Changed the loader to return the users data instead of only loading it. routes/app/settings/users/SettingsUsers.tsx Instead of using getLoaderInstance to get the data, I use getLoader, like so: const { users } = useLoader({ from: settingsUsersRoute.id }); Seems to work fine 🤷‍♂️
jan144
StackBlitz
tanstack-react-router-demo-useLoader - StackBlitz
React + TypeScript starter project

Did you find this page helpful?