How can I separate cache operations and side effects in a custom mutation hook? #276
-
I'm thinking, how I can separate some cache operations and side effects in a custom mutation hook. Now if both hook and mutation function have function App() {
const [mutate] = useMutation(() => "", {
onSuccess: () => console.log("useMutation") // will not fire
});
function handleClick() {
mutate({
onSuccess: () => console.log("mutate") // will fire
});
}
return <button onClick={handleClick}>Mutate</button>;
} I want to update cache on every mutation and also have side effects on some mutations like url redirect. The way to make it possible as I can see now is to execute both handlers. function useCustomMutation() {
return useMutation(() => "", {
// Update cache data on every mutation of this type
onSuccess: data => queryCache.setQueryData(...)
});
}
function App() {
const [mutate] = useCustomMutation();
function handleRedirectClick() {
mutate({
// Execute any side effects on some mutations
onSuccess: () => history.push(...)
});
}
function handleMutateClick() {
mutate();
}
return (
<>
<button onClick={handleMutateClick}>Mutate</button>
<button onClick={handleRedirectClick}>Mutate and redirect</button>
</>
);
} What do you think? Maybe there's a better idea? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Hmm. Good point. So you're saying instead of having them override the hook-level one, they should add on to it (so both would execute) |
Beta Was this translation helpful? Give feedback.
-
I just published a fix for this. My original intention was the functionality you are describing, so I consider this a bug. In the latest version, if both options are defined, they will both fire with the mutate-level handler first, then the hook-level handler. |
Beta Was this translation helpful? Give feedback.
I just published a fix for this. My original intention was the functionality you are describing, so I consider this a bug. In the latest version, if both options are defined, they will both fire with the mutate-level handler first, then the hook-level handler.