Skip to content

Instantly share code, notes, and snippets.

@Martinnord
Last active December 18, 2019 14:07
Show Gist options
  • Save Martinnord/436726b9afe855c3da584fa356b565c3 to your computer and use it in GitHub Desktop.
Save Martinnord/436726b9afe855c3da584fa356b565c3 to your computer and use it in GitHub Desktop.
Hook for mange cookie with universal-cookie lib
import { useState } from "react";
import Cookies, { CookieSetOptions, Cookie } from "universal-cookie";
export const useCookie = (key: string) => {
const cookies = new Cookies();
const [value, setValue] = useState(() => {
if (Boolean(cookies.get(key))) {
return cookies.get(key);
}
return null;
});
const handleSetValue = (value: Cookie, options: CookieSetOptions) => {
setValue(value);
cookies.set(key, value, options);
};
const handleRemoveValue = (options: CookieSetOptions) => cookies.remove(key, options);
return [value, handleSetValue, handleRemoveValue];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment