Open History to see the last commit
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>.
15 * This allows the devtools to be loaded only on the client and bypasses any server side rendering.
16 * @param fn - Imports the module whose default export is the component.
17 * @returns A component that renders `fallback` on the server and while the module loads on the
18 * client, then the imported component.
19 */
20export default function clientOnly<T extends Component<any>>(
21 fn: () => Promise<{
22 default: T
23 }>,
24) {
25 if (isServer)
26 return (props: ComponentProps<T> & { fallback?: JSX.Element }) =>
27 props.fallback
28β
29 const [comp, setComp] = createSignal<T>()
30 fn().then((m) => setComp(() => m.default))
31 return (props: ComponentProps<T>) => {
32 let Comp: T | undefined
33 let m: boolean
34 const [, rest] = splitProps(props, ['fallback'])
35 if ((Comp = comp()) && !sharedConfig.context) return Comp(rest)
36 const [mounted, setMounted] = createSignal(!sharedConfig.context)
37 onMount(() => setMounted(true))
38 return createMemo(
39 () => (
40 (Comp = comp()),
41 (m = mounted()),
42 untrack(() => (Comp && m ? Comp(rest) : props.fallback))
43 ),
44 )
45 }
46}