react-use
react-use copied to clipboard
Triggering Refresh to Cookie in `useCookie`
Is your feature request related to a problem? Please describe.
My cookie is changed by a request done in some API call. I need to react to that change. The new cookie value is not by useCookie() because it assumes that all changes are done through it.
Describe the solution you'd like
A refresh would probably suffice. Something like this:
import { useCallback, useState } from 'react';
import Cookies from 'js-cookie';
const useCookie = (
cookieName: string
): [string | null, (newValue: string, options?: Cookies.CookieAttributes) => void, () => void, () => void] => {
const [value, setValue] = useState<string | null>(() => Cookies.get(cookieName) || null);
const updateCookie = useCallback(
(newValue: string, options?: Cookies.CookieAttributes) => {
Cookies.set(cookieName, newValue, options);
setValue(newValue);
},
[cookieName]
);
const refreshCookie = useCallback(() => {
const newValue = Cookies.get(cookieName);
if (newValue === value) {
return;
}
if (newValue !== undefined) {
updateCookie(newValue);
} else {
deleteCookie();
}
}, [cookieName, updateCookie, value]);
const deleteCookie = useCallback(() => {
Cookies.remove(cookieName);
setValue(null);
}, [cookieName]);
return [value, updateCookie, deleteCookie, refreshCookie];
};
export default useCookie;
(not tested)
Usage:
const [value, update, delete, refresh] = useCookie("sessionData");
// ...
fetch("/settings/update").then(() => refresh());
Describe alternatives you've considered I'm open for suggestions
use this. https://www.reactuse.com/useCookie