Skip to content

Commit

Permalink
fix: update impl
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Nov 7, 2023
1 parent a4164ea commit e8bdba9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
23 changes: 14 additions & 9 deletions src/no-ssr/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
/** @see https://foxact.skk.moe/no-ssr */
export const noSSR = (extraMessage?: string) => {
if (typeof window === 'undefined') {
const error = new Error(extraMessage);
/** @private */
export const noSSRError = (errorMessage?: string) => {
const error = new Error(errorMessage);

// Next.js marks errors with `NEXT_DYNAMIC_NO_SSR_CODE` digest as recoverable:
// https://github.com/vercel/next.js/blob/ded28edeae16f8f8b4b9b117a83b5232e3623029/packages/next/src/client/on-recoverable-error.ts#L3
(error as any).digest = 'NEXT_DYNAMIC_NO_SSR_CODE';

// Next.js marks errors with `NEXT_DYNAMIC_NO_SSR_CODE` digest as recoverable:
// https://github.com/vercel/next.js/blob/ded28edeae16f8f8b4b9b117a83b5232e3623029/packages/next/src/client/on-recoverable-error.ts#L3
(error as any).digest = 'NEXT_DYNAMIC_NO_SSR_CODE';
(error as any).recoverableError = 'NO_SSR';

(error as any).recoverableError = 'NO_SSR';
return error;
};

throw error;
/** @see https://foxact.skk.moe/no-ssr */
export const noSSR = (extraMessage?: string) => {
if (typeof window === 'undefined') {
throw noSSRError(extraMessage);
}
};
6 changes: 4 additions & 2 deletions src/use-local-storage/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useSyncExternalStore, useCallback, useEffect } from 'react';
import { noop } from '../noop';
import { useIsomorphicLayoutEffect } from '../use-isomorphic-layout-effect';
import { noSSR } from '../no-ssr';
import { noSSRError } from '../no-ssr';

function dispatchStorageEvent(key: string, newValue: string | null) {
if (typeof window !== 'undefined') {
Expand Down Expand Up @@ -59,7 +59,9 @@ const subscribeToLocalStorage = (callback: () => void) => {
return noop;
};

const getServerSnapshotWithoutServerValue = () => noSSR('foxact: useLocalStorage without `serverValue` will only be used at client side.');
const getServerSnapshotWithoutServerValue = () => {
throw noSSRError('useLocalStorage cannot be used on the server without a serverValue');
};

// This type utility is only used for workaround https://github.com/microsoft/TypeScript/issues/37663
// eslint-disable-next-line @typescript-eslint/ban-types -- workaround TypeScript bug
Expand Down

0 comments on commit e8bdba9

Please sign in to comment.