Skip to content

Commit

Permalink
feat: add noSSR
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Nov 7, 2023
1 parent 361c4f7 commit 7780359
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/no-ssr/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const noSSR = (extraMessage?: string) => {
const error = new Error(extraMessage);

// 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';

throw error;
};
5 changes: 4 additions & 1 deletion src/use-local-storage/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useSyncExternalStore, useCallback, useEffect } from 'react';
import { noop } from '../noop';
import { useIsomorphicLayoutEffect } from '../use-isomorphic-layout-effect';
import { noSSR } from '../no-ssr';

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

const getServerSnapshotWithoutServerValue = () => noSSR('foxact: useLocalStorage without `serverValue` will only be used at client side.');

// 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
const isFunction = (x: unknown): x is Function => typeof x === 'function';
Expand All @@ -65,7 +68,7 @@ export const useLocalStorage = <T extends string | number>(key: string, serverVa
// If the serverValue is not provided, we don't pass it to useSES, which will cause useSES to opt-in client-side rendering
const getServerSnapshot = typeof serverValue !== 'undefined'
? () => JSON.stringify(serverValue)
: undefined;
: getServerSnapshotWithoutServerValue;

const store = useSyncExternalStore(
subscribeToLocalStorage,
Expand Down

0 comments on commit 7780359

Please sign in to comment.