T
TanStack11mo ago
stormy-gold

How can I call an unknown amount of useMutations or set MutationKey in mutateFn?

I need to set the mutationKey for each item so I track the loading status in another component. Correct me if I'm wrong, after reading the docs and some research. - there is no useMutations like useQueries which would allow me to create the useMutationObject and pass in the key for each useMutationObject - I cannot set the mutationKey in themutationFn Thank You! Unfortunately im on v4 for now My use case is as follows:
const useCreateEntitiesMutation = (id: string) => {
return useMutation({
mutationKey: ['createEntities',id],
mutationFn: async (itemId: string, body: any) => {
const res = await axios.post(`test.com/${itemId}`, body);
return res;
},
});
};

const EntitieDialog = (ids: string[]) => {
const {mutate} = useCreateMutation(id); // I cannot set multiple mutationKeys since you cannot loop a hook.

const handleSubmitAll = () => {
for (const id of ids) {
const data = {value: 'value'};
mutate(id, data);
}
};

return <button onClick={handleSubmitAll}>Submit</button>;
};


// use somehwere else
const EntitesListItem = (id:string)=>{
const isLoading = !!useIsMutating({
mutationKey: ['createEntities',id]
});
return <Item isLoading={isLoading}/>
}
const useCreateEntitiesMutation = (id: string) => {
return useMutation({
mutationKey: ['createEntities',id],
mutationFn: async (itemId: string, body: any) => {
const res = await axios.post(`test.com/${itemId}`, body);
return res;
},
});
};

const EntitieDialog = (ids: string[]) => {
const {mutate} = useCreateMutation(id); // I cannot set multiple mutationKeys since you cannot loop a hook.

const handleSubmitAll = () => {
for (const id of ids) {
const data = {value: 'value'};
mutate(id, data);
}
};

return <button onClick={handleSubmitAll}>Submit</button>;
};


// use somehwere else
const EntitesListItem = (id:string)=>{
const isLoading = !!useIsMutating({
mutationKey: ['createEntities',id]
});
return <Item isLoading={isLoading}/>
}
2 Replies
national-gold
national-gold11mo ago
I think predicate can help you here: https://tanstack.com/query/latest/docs/framework/react/guides/filters#mutation-filters
useIsMutating({
predicate: (mutation) => mutation.options.variables?.id === id,
})
useIsMutating({
predicate: (mutation) => mutation.options.variables?.id === id,
})
TanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.
From An unknown user
From An unknown user
stormy-gold
stormy-goldOP11mo ago
Thank you for replying so quickly. Just made a POC. This would work with my usecase!

Did you find this page helpful?