@bemit/consent-ui-react
Version:
59 lines • 1.5 kB
JavaScript
import React from 'react';
import { consentUi } from '@bemit/consent-ui/ConsentUi';
import { jsx as _jsx } from "react/jsx-runtime";
const ConsentUiContext = React.createContext([undefined]);
export const useConsent = () => React.useContext(ConsentUiContext);
export const ConsentUiProvider = ({
children,
Context = ConsentUiContext,
locale,
ownId,
definition
}) => {
const [state, setState] = React.useState(() => ({
...(consentUi()?.toState() || {})
}));
React.useEffect(() => {
const ui = consentUi();
if (!ui) return;
const off1 = ui.onConsent(() => {
setState(s => ({
...s,
...ui.toState(),
showUi: false
}));
});
return () => {
off1();
};
}, [setState]);
const giveConsent = React.useCallback((preferences = {}) => {
const ui = consentUi();
if (!ui) return;
ui.giveConsent(preferences);
}, []);
const updateConsent = React.useCallback((type, id, prefer) => {
const ui = consentUi();
if (!ui) return;
ui.updateConsent(type, id, prefer);
}, []);
const toggleUi = React.useCallback(() => {
setState(s => ({
...s,
showUi: !s.showUi
}));
}, [setState]);
const ctx = React.useMemo(() => ({
...state,
...definition,
locale,
ownId,
giveConsent,
updateConsent,
toggleUi
}), [definition, state, locale, ownId, giveConsent, updateConsent, toggleUi]);
return _jsx(Context.Provider, {
value: ctx,
children: children
});
};