useCookie hook breaking on build

Viewed 282

I'm using a custom hook to set, edit, and remove cookies on my Gatsby site:

use-cookie.ts

import { useState } from 'react';

const getItem = (key: string) => {
  if (typeof document !== undefined) {
    document.cookie.split('; ').reduce((total, currentCookie) => {
      const item = currentCookie.split('=');
      const storedKey = item[0];
      const storedValue = item[1];

      return key === storedKey ? decodeURIComponent(storedValue) : total;
    }, '');
  }
};

const setItem = (key: string, value: string | boolean, numberOfDays: number) => {
  const now = new Date();

  now.setTime(now.getTime() + numberOfDays * 60 * 60 * 24 * 1000);

  if (typeof document !== undefined) {
    document.cookie = `${key}=${value}; expires=${now.toUTCString()}; path=/`;
  }
};

export const useCookie = (key: string, defaultValue: string | boolean | any) => {
  const getCookie = () => (getItem(key), defaultValue);
  const [cookie, setCookie] = useState(getCookie());

  const updateCookie = (value: string, numberOfDays: number) => {
    setCookie(value);
    setItem(key, value, numberOfDays);
  };

  return [cookie, updateCookie];
};

I use it in a component like so:

const [initialCookieValue, updateCookieValue] = useCookie('cookie', false);

However, in spite of checking all of the references to document with if (typeof document !== undefined) my site is still breaking on build with WebpackError: ReferenceError: document is not defined. I have no clue what I'm doing wrong, or how to go about fixing it, but I know that the error goes away if I remove the hook.

Any ideas?

1 Answers

Check undefined as a string, 'undefined'.

  if (typeof document !== 'undefined')

Applied to your code:

import { useState } from 'react';

const getItem = (key: string) => {
  if (typeof document !== 'undefined') {
    document.cookie.split('; ').reduce((total, currentCookie) => {
      const item = currentCookie.split('=');
      const storedKey = item[0];
      const storedValue = item[1];

      return key === storedKey ? decodeURIComponent(storedValue) : total;
    }, '');
  }
};

const setItem = (key: string, value: string | boolean, numberOfDays: number) => {
  const now = new Date();

  now.setTime(now.getTime() + numberOfDays * 60 * 60 * 24 * 1000);

  if (typeof document !== 'undefined') {
    document.cookie = `${key}=${value}; expires=${now.toUTCString()}; path=/`;
  }
};

export const useCookie = (key: string, defaultValue: string | boolean | any) => {
  const getCookie = () => (getItem(key), defaultValue);
  const [cookie, setCookie] = useState(getCookie());

  const updateCookie = (value: string, numberOfDays: number) => {
    setCookie(value);
    setItem(key, value, numberOfDays);
  };

  return [cookie, updateCookie];
};
Related