Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

clientOnly.tsx

47 lines1.4 KB

1import {
2 createMemo,
3 createSignal,
4 isHydrating,
5 omit,
6 onSettled,
7 untrack,
8} from 'solid-js'
9import { isServer } from '@solidjs/web'
10import type { Component, ComponentProps } from 'solid-js'
11import type { JSX } from '@solidjs/web'
12​
13/**
14 * Loads the devtools only on the client, so that they bypass any server side rendering. Taken from
15 * [solid-start's codebase](https://github.com/solidjs/solid-start/blob/2967fc2db3f0df826f061020231dbdafdfa0746b/packages/start/islands/clientOnly.tsx).
16 * @param fn - Dynamically imports the module whose default export is the component.
17 * @returns A component that renders `props.fallback` on the server and until the import resolves.
18 */
19export default function clientOnly<T extends Component<any>>(
20 fn: () => Promise<{
21 default: T
22 }>,
23) {
24 if (isServer)
25 return (props: ComponentProps<T> & { fallback?: JSX.Element }) =>
26 props.fallback
27​
28 const [comp, setComp] = createSignal<T>()
29 fn().then((m) => setComp(() => m.default))
30 return (props: ComponentProps<T>) => {
31 let Comp: T | undefined
32 let m: boolean
33 const rest = omit(props, 'fallback')
34 if ((Comp = comp()) && !isHydrating()) return Comp(rest)
35 const [mounted, setMounted] = createSignal(!isHydrating())
36 onSettled(() => {
37 setMounted(true)
38 })
39 return createMemo(
40 () => (
41 (Comp = comp()),
42 (m = mounted()),
43 untrack(() => (Comp && m ? Comp(rest) : props.fallback))
44 ),
45 )
46 }