T
TanStack•7mo ago
fascinating-indigo

Calling API and updating search params before loading a route

Hi, I have a case where BEFORE loading a route I'd really like to make some API call to check something and then update the searchParams based on the result. Something like: click -> see loading -> API call in the background -> searchparams update -> route is loaded What's the best way to achieve that? I tried beforeLoad for context update, but in middleware I only have access to the search params and not to context
3 Replies
wise-white
wise-white•7mo ago
beforeLoad is the answer. throw a redirect to update search params
fascinating-indigo
fascinating-indigoOP•7mo ago
That's what I try:
beforeLoad: async ({ context: { queryClient }, search }) => {
const data = await queryClient.ensureQueryData(
getInitialMeeting(String(search.customer_id))
);
console.log({ data });
throw redirect({
from: '/choose-term',
to: '/choose-term',
search: (prev) => ({
...prev,
user_id: data.user_id,
}),
replace: true,
});
},
beforeLoad: async ({ context: { queryClient }, search }) => {
const data = await queryClient.ensureQueryData(
getInitialMeeting(String(search.customer_id))
);
console.log({ data });
throw redirect({
from: '/choose-term',
to: '/choose-term',
search: (prev) => ({
...prev,
user_id: data.user_id,
}),
replace: true,
});
},
and unfortunately I get into infinite loop - see gazillion of console.logs with data. What am I doing wrong? OK, I just need to check whether user_id is already set at the beginning of the beforeLoad 😅
if (search.acoustician_id) return;
if (search.acoustician_id) return;
wise-white
wise-white•7mo ago
yep

Did you find this page helpful?