unjs / unjs/ofetch

Custom hook support

Open
#332 0 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
5.4k
Forks
195
PR merge metrics
No merged PRs in 30d

Description

Describe the feature

It would be great to have a feature like custom hooks. At the moment, ofetch has interceptors and this is very convenient, but sometimes it feels like the functionality of $fetch is limited - this concerns the end use of $fetch.
For example, if we specify interceptors in the ofetch.create method - then in the final use case we can only override the interceptors. And just for such cases, when we need to make interceptors as shared, we can call hooks inside the interceptors.

For example, in the options we add hooks:

hooks?: {
  [key: string]: { (context: any): Promise<void> | void };
};

Inside the interceptor we call the hook:

onResponseError: async ({ response, options }) => {
  if (response.statusCode === 422) {
    await options.hooks?.validationErrors(response._data?.errors || [])
  }
}

Example of final $fetch call:

const { data, error } = await useFetch("login", {
  method: "POST",
  body: { emal: "test@test.com", password: "test1234" },
  hooks: {
    validationErrors: (errors) => form.value.setErrors(errors)
  }
});

Do you think this makes sense?

Additional information
  • Would you be willing to help implement this feature?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the existing ofetch.create interceptor options and the $fetch option flow described in the issue. Determine how custom hooks should be exposed and invoked alongside shared interceptors, then define tests covering hook registration, invocation, and the validationErrors example; done means the proposed hook behavior is implemented and documented.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
api
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.