From 32946a6d67920afe7d9e3846b41e70fbde6c10bf Mon Sep 17 00:00:00 2001 From: Ziyang Lin Date: Fri, 4 Apr 2025 18:02:37 +0200 Subject: [PATCH] feat: add useMultiMutation hook for managing multiple mutations in React --- src/useMultiMutation.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/useMultiMutation.ts diff --git a/src/useMultiMutation.ts b/src/useMultiMutation.ts new file mode 100644 index 0000000..166b622 --- /dev/null +++ b/src/useMultiMutation.ts @@ -0,0 +1,28 @@ +import { useState } from 'react'; +import { UseMutationResult } from 'react-query'; + +export function useMultiMutation(items: T[], expectedTotal?: number) { + const [mutations, setMutations] = useState>( + {}, + ); + + const handleMutationReady = (key: string, mutation: UseMutationResult) => { + setMutations((prev) => ({ + ...prev, + [key]: { + key, + ...mutation, + }, + })); + }; + + const targetCount = expectedTotal ?? items.length; + const isAllMutationsReady = + targetCount === 0 || Object.keys(mutations).length >= targetCount; + + return { + mutations, + handleMutationReady, + isAllMutationsReady, + }; +}