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

35 lines
903 B
TypeScript

import React from 'react';
import invariant from 'tiny-invariant';
import { AnyEndpoint, Method } from './endpoint';
import { LazyRequestConfigFromEndpoint, useLazyRequest } from './lazy-request-hook';
export type RequestConfigFromEndpoint<E extends AnyEndpoint> = Readonly<
LazyRequestConfigFromEndpoint<E>
& {
skip?: boolean,
}
>
export function useRequest<E extends AnyEndpoint>(
endpoint: E,
config?: RequestConfigFromEndpoint<E>,
) {
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;
}