use-http icon indicating copy to clipboard operation
use-http copied to clipboard

TS: Ability to add expected type for fetch body.

Open YoavHortman opened this issue 2 years ago • 1 comments

Currently useFetch only allows for one generic argument - the response body.

I suggest adding an optional second argument for the request body.

When using libraries like zod it's very useful to be able to strongly type the request body so that when it changes you don't have to go hunting, the issues will immediately pop up.

Below is an example of how I currently get around this constraint:

export const useTypedBodyFetch = <T, B extends BodyInit | object>(HOST: string) => {
  const all = useFetch<T>(HOST);

  const typedPost = (route: string, body: B) => {
    return all.post(route, body);
  };

  return { ...all, post: typedPost };
};

I think it would make to include this in the library.

Thanks.

YoavHortman avatar Dec 27 '23 15:12 YoavHortman

Feel free to submit a PR! :)

iamthesiz avatar Jan 03 '24 17:01 iamthesiz