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

clientOnly.tsx

48 lines1.6 KB

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