This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
react-rest-request/src/request-hook.ts

36 lines
903 B
TypeScript
Raw Normal View History

import React from 'react';
import invariant from 'tiny-invariant';
import { Endpoint, Method } from './endpoint';
import { LazyRequestConfig, useLazyRequest } from './lazy-request-hook';
export type RequestConfig<R, V, P> = Readonly<
LazyRequestConfig<R, V, P>
& {
skip?: boolean,
}
>
export function useRequest<R = Record<string, any>, V = Record<string, any>, P = void>(
endpoint: Endpoint<R, V, P>,
config?: RequestConfig<R, V, P>,
) {
invariant(
endpoint.method !== Method.DELETE,
`You cannot use useRequest with ${endpoint.method} method`
);
const [handler, state] = useLazyRequest(endpoint, config);
const skip = React.useMemo(() => config?.skip ?? false, [config]);
React.useEffect(
() => {
if (!skip) {
handler();
}
},
[skip, handler]
);
return state;
}