Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Triggering Refresh to Cookie in useCookie #2495

Open
nikeee opened this issue Apr 25, 2023 · 1 comment
Open

Triggering Refresh to Cookie in useCookie #2495

nikeee opened this issue Apr 25, 2023 · 1 comment

Comments

@nikeee
Copy link

nikeee commented Apr 25, 2023

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

@childrentime
Copy link

use this. https://www.reactuse.com/useCookie

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants