Skip to content

Allow passing arguments to run with useFetch #75

Closed
@phryneas

Description

@phryneas

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions