27 lines
668 B
TypeScript
27 lines
668 B
TypeScript
import { useState, useEffect, useCallback } from "react";
|
|
import type { CarouselApi } from "~/components/ui/carousel";
|
|
|
|
interface UseCarouselOptions {
|
|
onSelect?: (api: CarouselApi) => void;
|
|
}
|
|
|
|
export function useCarousel({ onSelect }: UseCarouselOptions = {}) {
|
|
const [api, setApi] = useState<CarouselApi | null>(null);
|
|
|
|
const onApiReady = useCallback((newApi: CarouselApi) => {
|
|
setApi(newApi);
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!api || !onSelect) return;
|
|
|
|
const handler = () => onSelect(api);
|
|
api.on("select", handler);
|
|
return () => {
|
|
api.off("select", handler);
|
|
};
|
|
}, [api, onSelect]);
|
|
|
|
return { api, setApi: onApiReady };
|
|
}
|