const submitHandler = useCallback(() => {
let count = 0
const runMutation = (product) => {
updateProduct({
variables: {
input: {
descriptionHtml: `${product.descriptionHtml}${descriptionValue}`,
title: `${product.title}${titleValue}`,
id: product.id
}
}
}).then((data) => {
console.log('Update product', count, data);
count++;
if(products[count]) runMutation(products[count])
else {
console.log('Update complete');
setShowToast(true);
}
})
}
runMutation(products[count])
}, [products, descriptionValue, titleValue]);
Topic summary
A developer is encountering a React hooks error while attempting to bulk update products. The code uses useCallback for a submitHandler function that iterates through products and calls a GraphQL mutation (updateProduct) to modify product titles and descriptions.
Technical Issue:
- The mutation function
runMutationis defined inside the callback but may be causing the hooks violation error - The code recursively calls
runMutationto process products sequentially
Proposed Solution:
- Wrap the
runMutationfunction itself inuseCallback - Pass
[updateProduct, products]as dependencies to the hook
This should resolve the invalid hook call error by properly memoizing the nested function according to React’s Rules of Hooks.
Wrap runMutation in useCallback, and pass [updateProduct, products] as the deps.
1 Like