
Security News
The Hidden Blast Radius of the Axios Compromise
The Axios compromise shows how time-dependent dependency resolution makes exposure harder to detect and contain.
react-mutation
Advanced tools
useMutation hook for React and React Native. Tailored for thorough response handling.
useMutation hook for React and React Native. Tailored for thorough response handling.
yarn add react-mutation
# or
npm i --save react-mutation
const Button = () => {
const [mutate, { isLoading, error, reset }] = useMutation(({ name }) => {
return Promise.resolve(`Hello ${name}!`)
}, {
chainSettle: x => x.catch(catchAllError)
})
return (
<button onClick={() => {
mutate({ name: "World" }, (chain) =>
chain.then((returnedString) => {
// On success
console.log(returnedString)
}).catch((e) => {
// On error
console.error(e)
})
)
}}>
Call Mutate
</button>
)
}
react-mutation?We expose isLoading and error in the hook level allowing us to show appropriate status to user.
react-mutation also allows great control over handling mutation responses. This library was built mainly for better error handling. We allow then and catch (or async/await try & catch) on all stages of the mutation.
These are:
Consider the following graph:

This library is tailored to allow promise chaining on various stages of the response. A standard flow could look like:
I don't recommend returning/throwing an error past "global" unless you know what you're doing. Eg: Catch using error boundary.
useMutation(mutationFn, config?)useMutation<TResult = any, TVariables = any>(mutationFn: (variables: TVariables) => Promise, config?: MutationParamConfig): MutationReturn<TResult, TVariables>
mutationFn: (variables: TVariables) => Promisevariables is an object that will be passed when you call the mutate functionconfig: MutationParamConfig{ onMutate, chainSettle }
onMutate: (variables: TVariables) => voidchainSettle: (chain: Promise, variables: TVariables) => Promise.catchchainSettle: (chain) => chain.catch(e => console.error(e))MutationReturn<TResult, TVariables>or equals to
MutationReturn<TResult, TVariables> = [
MutationReturnFunction<TResult, TVariables>,
MutationReturnConfig
]
MutationReturnFunction: (variables, chain?, overrideConfig?) => Promisevariables will be passed to mutationFnconst [mutate] = useMutation(...)
mutate(variables)
chain?: (chain: Promise, variables: TVariables) => Promisemutate(variables,
chain => chain.then(x => console.log(x))
)
overrideConfig?: MutationParamConfigMutationReturnConfig: { isLoading, error, reset }isLoading: true if mutation is being executed, otherwise falseerror: error object from .catch. null if no errorreset: function to reset error back to null. Eg: reset()This will call the error and log it, then let it be handled by catchAllError
api.ts
export default () => {
return useMutation(({ name }) => {
return Promise.reject()
}, {
chainSettle: x => x.catch(catchAllError)
})
}
component.tsx
import useApi from './api.ts'
const Button = () => {
const [mutate] = useApi()
return (
<button onClick={() => {
mutate({ name: "World" }, (chain) =>
chain.catch((e) => {
// On error
// This will be called first
console.error(e)
throw e
})
)
}}>
Call Mutate
</button>
)
}
api.ts
export default () => {
return useMutation(({ name }) => {
return new Promise((resolve, reject) => setTimeout(resolve(name), 1000))
})
}
component.tsx
import useApi from './api.ts'
const Button = () => {
const [mutate, { isLoading, error, reset }] = useApi()
return (
<>
{isLoading.toString()}
{error?.toString() ?? "null"}
<button onClick={() => {
mutate({ name: "World" })
}}>
Call Mutate
</button>
<button onClick={() => reset()}>Reset</button>
</>
)
}
export default () => {
return useMutation(({ name }) => {
return new Promise((resolve, reject) => setTimeout(resolve(name), 1000))
}, {
onMutate: (variables) => {
const { name } = variables
// Update cache
}
})
}
react-mutation is built using TS. You should be able to use it without doing anything.
Refer to src/types.ts for most of the types we use., so you don't have to do anything to use
Sometimes, we'll want to chain mutations together. When one failed, then the rest shouldn't continue. Here's an example of how you might do this:
const Button = () => {
const [mutate] = useMutation(({ name }) => {
return Promise.resolve(`Hello ${name}!`)
})
const [mutate2] = useMutation(({ name }) => {
return Promise.resolve(`Hello, my name is ${name}!`)
})
return (
<button onClick={async () => {
try {
await mutate({ name: "World" })
await mutate2({ name: "Adam" })
}
catch(e) {
alert("Mutate failed!")
}
}}>
Call Mutate
</button>
)
}
Notice that for this, we catch the error in a different way that normal. Usually we pass a chain function on the second parameter. Using await outside means that this is handled after the "global" handler. We let the error overflow and handle it ourself.
If you are using a catch-all error handling on the global level, then this wouldn't work. Since the error won't be thrown, an error in any of the mutate won't stop the rest from executing.
For this, we can override the global chain by passing additional config when we call mutate. I also recommend having a default error handling function that you can easily trigger whether to propegate the error or not.
Since we're just dealing with Promise, we can use async/await wherever we want. The only downside is it could be confusing which part of the promise are we dealing with.
api.ts
export default () => {
return useMutation(({ name }) => {
return new Promise((resolve, reject) => setTimeout(resolve(name), 1000))
})
}
component.tsx
import useApi from './api.ts'
const Button = () => {
const [mutate, { isLoading, error, reset }] = useApi()
return (
<>
{isLoading.toString()}
{error?.toString() ?? "null"}
<button onClick={() => {
mutate(
{ name: "World" },
async chain => {
console.log("This is called before request is run")
const res = await chain
console.log("This is called after request is run (Same as after .then)")
return res
}
)
}}>
Call Mutate
</button>
<button onClick={() => reset()}>Reset</button>
</>
)
}
Any contributions are welcomed. Create an issue/PR and I'll have a look at it as soon as possible. I'd love to see use cases and problems when using this.
Big thanks to react-query where a big part of our API is based from.
FAQs
useMutation hook for React and React Native. Tailored for thorough response handling.
We found that react-mutation demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
The Axios compromise shows how time-dependent dependency resolution makes exposure harder to detect and contain.

Research
A supply chain attack on Axios introduced a malicious dependency, plain-crypto-js@4.2.1, published minutes earlier and absent from the project’s GitHub releases.

Research
Malicious versions of the Telnyx Python SDK on PyPI delivered credential-stealing malware via a multi-stage supply chain attack.