question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Allow passing arguments to `run` with useFetch

See original GitHub issue

Hi 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:closed
  • Created 4 years ago
  • Comments:7 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
ghengeveldcommented, Sep 14, 2019

I opened #111 to resolve this.

1reaction
ghengeveldcommented, Sep 14, 2019

@iamandyk Good question! I thought this was possible, but upon further investigation, it turns out you can’t, at least not using useFetch with run and passing an init object. The first argument currently has to be a string url, and it’s impossible to override this using a url prop in the init object.

For the time being you can fall back to using useAsync instead of useFetch, which allows you to do this:

import { useAsync } from "react-async"

const loadCustomer = async ([id], props, { signal }) => {
  const res = await fetch(`/api/customers?id=${id}`, { signal })
  if (!res.ok) throw new Error(res)
  return res.json()
}

const MyComponent = () => {
  const { data, run } = useAsync({ deferFn: loadCustomer })

  return (
    <div>
      {[1, 2, 3].map(id => <Button onClick={() => run(id)}>load #{id}</Button>}
    </div>
  )
}

We’ll have to update useFetch to allow overriding the url through init.

Read more comments on GitHub >

github_iconTop Results From Across the Web

useFetch
This fetch is run onMount/componentDidMount . The last argument [] means it will run onMount . If you pass it a variable like...
Read more >
Custom Hooks in React: useFetch - Alyssa Holland's Blog
It returns a Promise that resolves to the Response of that request. Additionally, you can pass in a second argument, options , that...
Read more >
Use Fetch to pass parameters and display response in react ...
I want to pass a username and password to an API. My code allows a user to login and the API can check...
Read more >
useFetch - VueUse
Using a ref for the url parameter will allow the useFetch function to ... will only run when the newly spawned instance do...
Read more >
React Custom Hook - useFetch - DEV Community ‍ ‍
That's a lot of code. Let's move most of it. The New Way. We'll create another file called useFetch.js . You want to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found