1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-10-09 11:14:29 +02:00
unleash.unleash/frontend/src/hooks/api/getters/useStrategy/useStrategy.ts
olav 523807359e fix: sort strategy parameters payload (#1218)
* refactor: improve useStrategy fetch hook

* fix: sort strategy parameters payload

* refactor: move React import to the top

* refactor: fix refetchStrategy name
2022-08-12 14:49:26 +02:00

41 lines
1.1 KiB
TypeScript

import useSWR from 'swr';
import { useCallback } from 'react';
import { formatApiPath } from 'utils/formatPath';
import { IStrategy } from 'interfaces/strategy';
import handleErrorResponses from '../httpErrorResponseHandler';
interface IUseStrategyOutput {
strategyDefinition?: IStrategy;
refetchStrategy: () => void;
loading: boolean;
error?: Error;
}
export const useStrategy = (
strategyName: string | undefined
): IUseStrategyOutput => {
const { data, error, mutate } = useSWR(
strategyName
? formatApiPath(`api/admin/strategies/${strategyName}`)
: null, // Don't fetch until we have a strategyName.
fetcher
);
const refetchStrategy = useCallback(() => {
mutate().catch(console.warn);
}, [mutate]);
return {
strategyDefinition: data,
refetchStrategy,
loading: !error && !data,
error,
};
};
const fetcher = (path: string): Promise<IStrategy> => {
return fetch(path)
.then(handleErrorResponses('Strategy'))
.then(res => res.json());
};