Allow passing arguments to `run` with useFetch
See original GitHub issueHi there,
I have the following use case:
I want to use useAsyncFetch in a function component with formik.
That looks something like this:
function MyForm() {
const { run } = useFetch(
"https://example.com",
{ method: "POST" },
{ defer: true }
);
return (
<div>
<h1>My Form</h1>
<Formik
initialValues={{ name: "jared" }}
onSubmit={(values, actions) => {
console.log('submitting', values)
// I want to submit here
run({ body: JSON.stringify(values) } /* this is currently not possible */).then(() =>
actions.setSubmitting(false)
);
}}
render={props => (
<form onSubmit={props.handleSubmit}>
<Field type="text" name="name" placeholder="Name" />
<button type="submit">Submit</button>
</form>
)}
/>
</div>
);
}
But currently, that doesn’t work, because I have no way of passing arguments into run that actually reflect in the fetch call - and since my values are only available within the onSubmit callback of formik, I have no way of accessing those in the outer scope where useFetch is called.
(Of course, this can be worked around by keeping init in a ref and modifying it before calling run, but that’s really smelly)
So my suggestion would be to use the first argument of this function that is currently unused to allow passing an argument that will be spread over init, before the request is sent.
Would something like this be feasible? I’d be happy to do a PR if this is something you’d accept.
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (6 by maintainers)

Top Related StackOverflow Question
I opened #111 to resolve this.
@iamandyk Good question! I thought this was possible, but upon further investigation, it turns out you can’t, at least not using
useFetchwithrunand passing aninitobject. The first argument currently has to be a string url, and it’s impossible to override this using aurlprop in theinitobject.For the time being you can fall back to using
useAsyncinstead ofuseFetch, which allows you to do this:We’ll have to update
useFetchto allow overriding theurlthroughinit.