1 line
1.6 KiB
JSON
1 line
1.6 KiB
JSON
{"ast":null,"code":"import { useContext, useEffect, useState, useRef, useMemo } from 'react';\nimport CookiesContext from './CookiesContext';\nexport default function useCookies(dependencies) {\n var cookies = useContext(CookiesContext);\n\n if (!cookies) {\n throw new Error('Missing <CookiesProvider>');\n }\n\n var initialCookies = cookies.getAll();\n\n var _a = useState(initialCookies),\n allCookies = _a[0],\n setCookies = _a[1];\n\n var previousCookiesRef = useRef(allCookies);\n useEffect(function () {\n function onChange() {\n var newCookies = cookies.getAll();\n\n if (shouldUpdate(dependencies || null, newCookies, previousCookiesRef.current)) {\n setCookies(newCookies);\n }\n\n previousCookiesRef.current = newCookies;\n }\n\n cookies.addChangeListener(onChange);\n return function () {\n cookies.removeChangeListener(onChange);\n };\n }, [cookies]);\n var setCookie = useMemo(function () {\n return cookies.set.bind(cookies);\n }, [cookies]);\n var removeCookie = useMemo(function () {\n return cookies.remove.bind(cookies);\n }, [cookies]);\n return [allCookies, setCookie, removeCookie];\n}\n\nfunction shouldUpdate(dependencies, newCookies, oldCookies) {\n if (!dependencies) {\n return true;\n }\n\n for (var _i = 0, dependencies_1 = dependencies; _i < dependencies_1.length; _i++) {\n var dependency = dependencies_1[_i];\n\n if (newCookies[dependency] !== oldCookies[dependency]) {\n return true;\n }\n }\n\n return false;\n}","map":null,"metadata":{},"sourceType":"module"} |