Skip to content

Commit

Permalink
feat: use React.use API
Browse files Browse the repository at this point in the history
  • Loading branch information
himself65 committed May 3, 2023
1 parent 589550b commit 68d927b
Showing 1 changed file with 43 additions and 2 deletions.
45 changes: 43 additions & 2 deletions core/use-swr.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { useCallback, useRef, useDebugValue, useMemo } from 'react'
/// <reference types="react/experimental" />
import ReactExports, {
useCallback,
useRef,
useDebugValue,
useMemo
} from 'react'
import { useSyncExternalStore } from 'use-sync-external-store/shim/index.js'

import {
Expand Down Expand Up @@ -36,6 +42,37 @@ import type {
GlobalState
} from 'swr/_internal'

const use =
ReactExports.use ||
(<T>(
promise: Promise<T> & {
status?: 'pending' | 'fulfilled' | 'rejected'
value?: T
reason?: unknown
}
): T => {
if (promise.status === 'pending') {
throw promise
} else if (promise.status === 'fulfilled') {
return promise.value as T
} else if (promise.status === 'rejected') {
throw promise.reason
} else {
promise.status = 'pending'
promise.then(
v => {
promise.status = 'fulfilled'
promise.value = v
},
e => {
promise.status = 'rejected'
promise.reason = e
}
)
throw promise
}
})

const WITH_DEDUPE = { dedupe: true }

type DefinitelyTruthy<T> = false extends T
Expand Down Expand Up @@ -661,7 +698,11 @@ export const useSWRHandler = <Data = any, Error = any>(
fetcherRef.current = fetcher
configRef.current = config
unmountedRef.current = false
throw isUndefined(error) ? revalidate(WITH_DEDUPE) : error
if (isUndefined(error)) {
use(revalidate(WITH_DEDUPE))
} else {
throw error
}
}

return {
Expand Down

0 comments on commit 68d927b

Please sign in to comment.