T
TanStack8mo ago
exotic-emerald

Is there a way to invalidate a query from a tanstack start server function

I'm using react query with tanstack start and I am redirecting from the server function straight but I need to invalidate the query I don't know if that is possible or I would need to stop redirecting from the server function completely
6 Replies
other-emerald
other-emerald8mo ago
Show some code?
exotic-emerald
exotic-emeraldOP8mo ago
I have this on the frontend
const { mutate, isPending } = useMutation({
mutationKey: ["createListing"],
mutationFn: async (data: z.infer<typeof createListingSchema>) => {
const formData = new FormData();

// Add all text/number fields
for (const [key, value] of Object.entries(data)) {
if (key !== "images" && value !== undefined) {
formData.append(key, value.toString());
}
}

// Add images
if (data.images) {
for (const file of Array.from(data.images)) {
formData.append("images", file);
}
}
console.log(data);

return $createListing({ data: formData });
},
onSuccess() {
toast.success("Listing created successfully");
},
});
const { mutate, isPending } = useMutation({
mutationKey: ["createListing"],
mutationFn: async (data: z.infer<typeof createListingSchema>) => {
const formData = new FormData();

// Add all text/number fields
for (const [key, value] of Object.entries(data)) {
if (key !== "images" && value !== undefined) {
formData.append(key, value.toString());
}
}

// Add images
if (data.images) {
for (const file of Array.from(data.images)) {
formData.append("images", file);
}
}
console.log(data);

return $createListing({ data: formData });
},
onSuccess() {
toast.success("Listing created successfully");
},
});
The server function
export const $createListing = createServerFn({
method: "POST",
})
.middleware([validateSellerMiddleware])
// Commented out the validator
.handler(async ({ context, data }) => {
const processedImages = await Promise.all(
data.images.map(async (file) => {
const processed = await processImage(file);
const key = `listings/${context.seller.id}/${crypto.randomUUID()}`;

const uploadResult = await uploadToStorage({
file,
key,
contentType: file.type,
});

return {
...uploadResult,
blurhash: processed.blurhash,
size: file.size,
};
}),
);

console.log({ data, seller: context.seller });

// Modified insert statement
await db.insert(schema.carListings).values({
make: data.make,
model: data.model,
year: data.year,
condition: data.condition,
price: data.price,
mileage: data.mileage.toString(),
transmission: data.transmission,
fuelType: data.fuelType,
description: data.description || null,
category: data.category,
location: data.location,
vin: data.vin || null,
sellerId: context.seller.id,
images: processedImages,
status: "active",
});

throw setCookieAndRedirect({
intent: "success",
message: "Listing created successfully",
description: "Your car listing has been created and is now active",
to: "/listings",
});
});
export const $createListing = createServerFn({
method: "POST",
})
.middleware([validateSellerMiddleware])
// Commented out the validator
.handler(async ({ context, data }) => {
const processedImages = await Promise.all(
data.images.map(async (file) => {
const processed = await processImage(file);
const key = `listings/${context.seller.id}/${crypto.randomUUID()}`;

const uploadResult = await uploadToStorage({
file,
key,
contentType: file.type,
});

return {
...uploadResult,
blurhash: processed.blurhash,
size: file.size,
};
}),
);

console.log({ data, seller: context.seller });

// Modified insert statement
await db.insert(schema.carListings).values({
make: data.make,
model: data.model,
year: data.year,
condition: data.condition,
price: data.price,
mileage: data.mileage.toString(),
transmission: data.transmission,
fuelType: data.fuelType,
description: data.description || null,
category: data.category,
location: data.location,
vin: data.vin || null,
sellerId: context.seller.id,
images: processedImages,
status: "active",
});

throw setCookieAndRedirect({
intent: "success",
message: "Listing created successfully",
description: "Your car listing has been created and is now active",
to: "/listings",
});
});
The route I am redirecting to has a query before I redirect is there a way I can invalidate the query on that page so it refetches or will I need to redirect on the frontend?
other-emerald
other-emerald8mo ago
Wrap the server function const $yourBoundServerFn = useServerFn(yourServerFn) The use that That will handle the redirect without killing your side effects
exotic-emerald
exotic-emeraldOP8mo ago
Since I'm redirecting will the onSuccess run That's the issue I'm worried about since I'm redirecting from the server function will the onSuccess for use mutation run at all?
other-emerald
other-emerald8mo ago
It should Redirects are handled by that hook and allow the happy path to continue Yep
other-emerald
other-emerald8mo ago
GitHub
router/packages/start/src/client/useServerFn.ts at 2d182c74412dad71...
🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering. - TanStack/router

Did you find this page helpful?