Return the result of a mutation

I'm trying return the id (which is a cuid that gets generated in the database) of an addProduct mutation back to the client. I get undefined if I fire the mutation once. Then I get the result of the first mutation if I fire the mutation a second time. Do I need a separate query to search for the the newly created item or is there a way to get the actual id of the first mutation upon firing the first mutation? const { data: createdProduct, mutateAsync: createProduct } = trpc.product.addProduct.useMutation();
async () => {
await createProduct({ productName: "Draft" });
console.log("createdProduct: ", createdProduct);
}
async () => {
await createProduct({ productName: "Draft" });
console.log("createdProduct: ", createdProduct);
}
This is what I'm returning in the router:
return prisma.Product.create({
data: {
createdBy: {
connect: {
id: userId,
},
},
name: input.productName,
},
});
return prisma.Product.create({
data: {
createdBy: {
connect: {
id: userId,
},
},
name: input.productName,
},
});
3 Replies
cje
cje3y ago
this works
jix74
jix74OP3y ago
@cje works 👍
cje
cje3y ago
explanation: regular mutate returns a promise, so the new data doesn't exist yet you can access the data you sent from within the onMutate/onSuccess/etc callbacks, but it will only have the data you sent on it, not stuff that's generated on the backend like ID etc

Did you find this page helpful?