T
TanStack4y ago
harsh-harlequin

Mutation onSuccess doesn't have ID returned from server

I'm trying to navigate to a newly created page on mutation success, but there is an ID missing.
const addDeliveryTypeMutation = useMutation({
mutationFn: addDeliveryType,
onSuccess: (data, variables, error, context) => {
console.log('error', error)
console.log('context', context);
console.log('variables', variables);
console.log('data', data);
// queryClient.invalidateQueries('deliveryTypes');
history.push(`/content/delivery/types/${data.id}`);
},
});
const addDeliveryTypeMutation = useMutation({
mutationFn: addDeliveryType,
onSuccess: (data, variables, error, context) => {
console.log('error', error)
console.log('context', context);
console.log('variables', variables);
console.log('data', data);
// queryClient.invalidateQueries('deliveryTypes');
history.push(`/content/delivery/types/${data.id}`);
},
});
I could modify addDeliveryType response to change the ID field to a different name (like "newId"), but this is not ideal.
export const addDeliveryType = async (deliveryType) => {
const response = await axios.post('/delivery/type', deliveryType);
return { ...response.data, newId: response.data.id };
};
export const addDeliveryType = async (deliveryType) => {
const response = await axios.post('/delivery/type', deliveryType);
return { ...response.data, newId: response.data.id };
};
Any ideas on how to do that properly?
6 Replies
foreign-sapphire
foreign-sapphire4y ago
Generally you should not return anything in body of POST requests
harsh-harlequin
harsh-harlequinOP4y ago
How else would you get the ID of the newly created item on the server? That ID is automatically generated when stored in MySQL.
rival-black
rival-black4y ago
Because you use axios, the data in the onSuccess field is an AxiosResponse, and AxiosResponse has a field called data as well. So you would access the id with data.data.id
correct-apricot
correct-apricot4y ago
Really? Is this a thing?
foreign-sapphire
foreign-sapphire4y ago
Well this is what HTTP spec says about POST 'If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30)' http://www.ietf.org/rfc/rfc2616.txt
harsh-harlequin
harsh-harlequinOP4y ago
I actually have other information from the response in the onSuccess data object only the ID is not there because it seems like is used internally for caching and has been removed when passed to the onSuccess function. I can still get it if I want with that code snippet, but if it has to be renamed to something else, such as newId then it works fine. Exactly status of the request and refers to the new resource where the new resource should be the one generated on the server with ID. I don't see your point.

Did you find this page helpful?