Skip to content

Commit

Permalink
feat: add
Browse files Browse the repository at this point in the history
  • Loading branch information
snakeUni committed May 10, 2023
1 parent f15c632 commit d6ac46d
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# useSuspense

三行代码实现 suspense fetch,兼容 SSR
几行代码实现 suspense fetch,兼容 SSR

## Install

Expand All @@ -22,7 +22,7 @@ const resolve = () => {
}

function App() {
const value = useSuspense(() => resolve())
const [_, value] = useSuspense(() => resolve())
}
```

Expand All @@ -42,7 +42,7 @@ const resolve = () => {
function App() {
const [name, setName] = useState('snake')
// 每次 name 变化触发重新请求
const value = useSuspense(() => resolve(), { name })
const [isPending, value] = useSuspense(() => resolve(), { name })
}
```

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "suspense-use",
"version": "1.0.0",
"version": "1.1.0",
"main": "lib/index.js",
"module": "es/index.js",
"scripts": {
Expand Down
10 changes: 7 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import React, { useMemo } from 'react'
import React, { useMemo, useDeferredValue } from 'react'

export function useSuspense<T = any>(
callback: () => Promise<T>,
params: Record<string, any> = {}
) {
const memoValue = useMemo(() => callback(), [JSON.stringify(params)])
return (React as any).use(memoValue)
const rawParams = JSON.stringify(params)
const deferredParam = useDeferredValue(rawParams)
const memoValue = useMemo(() => callback(), [deferredParam])
const isSuspending = deferredParam !== rawParams

return [isSuspending, (React as any).use(memoValue)]
}

0 comments on commit d6ac46d

Please sign in to comment.