UNPKG

@scaleway/use-analytics

Version:

A small hook to handle events analytics

59 lines (58 loc) 1.79 kB
import { useState, useEffect } from "react"; const timeout = (time) => { const controller = new AbortController(); setTimeout(() => { controller.abort(); }, time * 1e3); return controller; }; const transformConfigToDestinations = (config) => { const { destinations } = config.source; const dest = destinations.map( ({ destinationDefinition, config: { consentManagement } }) => ({ consents: consentManagement.flatMap( ({ consents }) => consents.map(({ consent }) => consent) ), displayName: destinationDefinition.displayName, name: destinationDefinition.name }) ); return dest; }; const useDestinations = (config) => { const [destinations, setDestinations] = useState(void 0); useEffect(() => { const fetchDestinations = async () => { if (config.analytics?.cdnURL && config.analytics.writeKey) { const url = `${config.analytics.cdnURL}/sourceConfig`; const WRITE_KEY = window.btoa(`${config.analytics.writeKey}:`); const response = await fetch(url, { headers: { Authorization: `Basic ${WRITE_KEY}` }, method: "GET", // We'd rather have an half consent than no consent at all signal: timeout(10).signal }); if (!response.ok) { throw new Error("Failed to fetch integrations from source"); } const json = await response.json(); return transformConfigToDestinations(json); } return []; }; fetchDestinations().then((response) => { setDestinations(response); }).catch(() => { setDestinations([]); }); }, [setDestinations, config.analytics]); return { destinations, isLoaded: destinations !== void 0 }; }; export { useDestinations };