70 lines
2.1 KiB
TypeScript
70 lines
2.1 KiB
TypeScript
![]() |
import { CreatePromocodeBody, Promocode } from "@root/model/promocodes";
|
||
|
import { enqueueSnackbar } from "notistack";
|
||
|
import useSwr, { mutate } from "swr";
|
||
|
import { promocodeApi } from "./requests";
|
||
|
|
||
|
export function usePromocodes() {
|
||
|
return useSwr(
|
||
|
"promocodes",
|
||
|
() => promocodeApi.getPromocodeList({
|
||
|
limit: 100,
|
||
|
filter: {
|
||
|
active: true,
|
||
|
},
|
||
|
page: 0,
|
||
|
}),
|
||
|
{
|
||
|
onError(err) {
|
||
|
console.log("Error fetching promocodes", err);
|
||
|
enqueueSnackbar(err.message, { variant: "error" });
|
||
|
},
|
||
|
focusThrottleInterval: 60e3,
|
||
|
}
|
||
|
);
|
||
|
}
|
||
|
|
||
|
export async function createPromocode(body: CreatePromocodeBody) {
|
||
|
try {
|
||
|
await mutate<Promocode[] | undefined, Promocode>(
|
||
|
"promocodes",
|
||
|
promocodeApi.createPromocode(body),
|
||
|
{
|
||
|
populateCache(result, currentData) {
|
||
|
if (!currentData) return;
|
||
|
|
||
|
return [...currentData, result];
|
||
|
},
|
||
|
revalidate: false,
|
||
|
}
|
||
|
);
|
||
|
} catch (error) {
|
||
|
console.log("Error creating promocode", error);
|
||
|
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export async function deletePromocode(id: string) {
|
||
|
try {
|
||
|
await mutate<Promocode[] | undefined, void>(
|
||
|
"promocodes",
|
||
|
promocodeApi.deletePromocode(id),
|
||
|
{
|
||
|
optimisticData(currentData, displayedData) {
|
||
|
if (!displayedData) return;
|
||
|
|
||
|
return displayedData.filter((item) => item.id !== id);
|
||
|
},
|
||
|
rollbackOnError: true,
|
||
|
populateCache(result, currentData) {
|
||
|
if (!currentData) return;
|
||
|
|
||
|
return currentData.filter((item) => item.id !== id);
|
||
|
},
|
||
|
}
|
||
|
);
|
||
|
} catch (error) {
|
||
|
console.log("Error deleting promocode", error);
|
||
|
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
||
|
}
|
||
|
}
|