While promiseFn is used for automatic data fetching on render, deferFn is used for asynchronous actions that must be triggered manually (e.g., submitting a form).
To use deferFn:
- Define a function that returns a Promise. This function receives three arguments:
args (an array of arguments passed to run), props, and signal (an AbortSignal). - Pass this function to the
deferFn option in useAsync. - Call the
run function returned by useAsync to trigger the action. You can pass any number of arguments to run, which will appear in the args array inside your deferFn.
This pattern is ideal for POST requests, deletions, or any action that should not happen automatically when a component mounts.
import React, { useState } from "react"
import { useAsync } from "react-async"
// The deferFn receives (args, props, { signal })
const subscribe = ([email], props, { signal }) =>
fetch("/newsletter", { method: "POST", body: JSON.stringify({ email }), signal })
const NewsletterForm = () => {
// deferFn is NOT automatically invoked on render
const { isPending, error, run } = useAsync({ deferFn: subscribe })
const [email, setEmail] = useState("")
const handleSubmit = event => {
event.preventDefault()
// Triggering the action manually with run()
run(email)
}
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={event => setEmail(event.target.value)} />
<button type="submit" disabled={isPending}>
Subscribe
</button>
{error && <p>{error.message}</p>}
</form>
)
}