Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 65880d2

Browse files
committed
fix: fix dynamic hoc
1 parent cfc18a0 commit 65880d2

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

framework/react/hoc.ts

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,16 @@ import {
22
createElement,
33
ComponentType,
44
ExoticComponent,
5-
Fragment,
6-
ReactNode,
5+
ReactChild,
6+
ReactElement,
7+
ReactFragment,
8+
ReactPortal,
79
useEffect,
810
useState
911
} from 'https://esm.sh/react'
1012
import { useDeno, useRouter } from './hooks.ts'
11-
import util from '../../shared/util.ts'
13+
14+
type ReactNode = ReactChild | ReactFragment | ReactPortal
1215

1316
/**
1417
* `withRouter` allows you to use `useRouter` hook with class component.
@@ -53,30 +56,38 @@ export function withDeno<T>(callback: () => (T | Promise<T>), revalidate?: numbe
5356
}
5457
}
5558

59+
/**
60+
* `dynamic` allows you to load a component asynchronously.
61+
*
62+
* ```tsx
63+
* const MyLogo = dynamic(() => import('~/components/logo.tsx'))
64+
* export default function Logo() {
65+
* return <MyLogo fallback={<p>loading...</p>}/>
66+
* }
67+
* ```
68+
*
69+
* @param {Function} factory - load factory.
70+
*/
5671
export function dynamic<T extends ComponentType<any>>(
5772
factory: () => Promise<{ default: T }>
5873
): ExoticComponent<T & { fallback?: ReactNode }> {
5974
const DynamicComponent = ({ fallback, ...props }: T & { fallback?: ReactNode }) => {
60-
const [Component, setComponent] = useState<T | null>(null)
75+
const [mod, setMod] = useState<{ default: T } | null>(null)
6176

6277
useEffect(() => {
63-
factory().then(mod => {
64-
setComponent(mod.default)
65-
})
78+
factory().then(setMod)
6679
}, [])
6780

68-
if (Component !== null) {
69-
return createElement(Component, props)
81+
if (mod !== null) {
82+
return createElement(mod.default, props)
7083
}
7184

7285
if (fallback) {
73-
return createElement(Fragment, null, fallback)
86+
return fallback as unknown as ReactElement
7487
}
7588

7689
return null
7790
}
7891

79-
DynamicComponent.$$typeof = util.supportSymbolFor ? Symbol.for('react.element') : (0xeac7 as unknown as symbol)
80-
81-
return DynamicComponent
92+
return DynamicComponent as ExoticComponent<any>
8293
}

0 commit comments

Comments
 (0)