TanStackT
TanStack16mo ago
2 replies
popular-magenta

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}/> 
}
Was this page helpful?