8000 feat: Improve global suspense-enabled `data` type by oosawy · Pull Request #4126 · vercel/swr · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: Improve global suspense-enabled data type #4126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions examples/suspense-global/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Basic

## One-Click Deploy

Deploy your own SWR project with Vercel.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?s=https://github.com/vercel/swr/tree/main/examples/suspense)

## How to Use

Download the example:

```bash
curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/suspense
cd suspense
```

Install it and run:

```bash
yarn
yarn dev
# or
npm install
npm run dev
```

## The Idea behind the Example

Show how to use the SWR suspense option with React suspense.
17 changes: 17 additions & 0 deletions examples/suspense-global/components/error-handling.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React from 'react'

export default class ErrorBoundary extends React.Component<any> {
state = { hasError: false, error: null }
static getDerivedStateFromError(error: any) {
return {
hasError: true,
error
}
}
render() {
if (this.state.hasError) {
return this.props.fallback
}
return this.props.children
}
}
24 changes: 24 additions & 0 deletions examples/suspense-global/global-swr-config.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use client'

import { SWRConfig } from 'swr'

import fetcher from './libs/fetch'

declare module 'swr' {
interface SWRGlobalConfig {
suspense: true
}
}

export function GlobalSWRConfig({ children }: { children: React.ReactNode }) {
return (
<SWRConfig
value={{
fetcher,
suspense: true
}}
>
{children}
</SWRConfig>
)
}
8 changes: 8 additions & 0 deletions examples/suspense-global/libs/fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export default async function fetcher(...args: [any]) {
const res = await fetch(...args)
if (!res.ok) {
throw new Error('An error occurred while fetching the data.')
} else {
return res.json()
}
}
5 changes: 5 additions & 0 deletions examples/suspense-global/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information.
17 changes: 17 additions & 0 deletions examples/suspense-global/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "suspense-global",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"next": "latest",
"react": "latest",
"react-dom": "latest",
"swr": "latest"
},
"scripts": {
"dev": "next",
"start": "next start",
"build": "next build"
}
}
30 changes: 30 additions & 0 deletions examples/suspense-global/pages/[user]/[repo].tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import dynamic from 'next/dynamic'
import Link from 'next/link'
import { Suspense } from 'react'
import ErrorHandling from '../../components/error-handling'
import { useRouter } from 'next/router'

const Detail = dynamic(() => import('./detail'), {
ssr: false
})

export default function Repo() {
const router = useRouter()
if (!router.isReady) return null
const { user, repo } = router.query
const id = `${user}/${repo}`

return (
<div style={{ textAlign: 'center' }}>
<h1>{id}</h1>
<Suspense fallback={<div>loading...</div>}>
<ErrorHandling fallback={<div>oooops!</div>}>
<Detail id={id}></Detail>
</ErrorHandling>
</Suspense>
<br />
<br />
<Link href="/">Back</Link>
</div>
)
}
20 changes: 20 additions & 0 deletions examples/suspense-global/pages/[user]/detail.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import useSWR from 'swr'
import { RepoData } from '../api/data'

const Detail = ({ id }: { id: string }) => {
const { data } = useSWR<RepoData>('/api/data?id=' + id)

return (
<>
{data ? (
<div>
<p>forks: {data.forks_count}</p>
<p>stars: {data.stargazers_count}</p>
<p>watchers: {data.watchers}</p>
</div>
) : null}
</>
)
}

export default Detail
10 changes: 10 additions & 0 deletions examples/suspense-global/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { AppProps } from 'next/app'
import { GlobalSWRConfig } from 'global-swr-config'

export default function MyApp({ Component, pageProps }: AppProps) {
return (
<GlobalSWRConfig>
<Component {...pageProps} />
</GlobalSWRConfig>
)
}
40 changes: 40 additions & 0 deletions examples/suspense-global/pages/api/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { NextApiRequest, NextApiResponse } from 'next'

const projects = [
'facebook/flipper',
'vuejs/vuepress',
'rust-lang/rust',
'vercel/next.js',
'emperor/clothes'
] as const

export type ProjectsData = typeof projects

export interface RepoData {
forks_count: number
stargazers_count: number
watchers: number
}

export default function api(req: NextApiRequest, res: NextApiResponse) {
if (req.query.id) {
if (req.query.id === projects[4]) {
setTimeout(() => {
res.status(404).json({ msg: 'not found' })
})
} else {
// a slow endpoint for getting repo data
fetch(`https://api.github.com/repos/${req.query.id}`)
.then(res => res.json())
.then(data => {
setTimeout(() => {
res.json(data)
}, 2000)
})
}
} else {
setTimeout(() => {
res.json(projects)
}, 2000)
}
}
17 changes: 17 additions & 0 deletions examples/suspense-global/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Suspense } from 'react'
import dynamic from 'next/dynamic'

const Repos = dynamic(() => import('./repos'), {
ssr: false
})

export default function Index() {
return (
<div style={{ textAlign: 'center' }}>
<h1>Trending Projects</h1>
<Suspense fallback={<div>loading...</div>}>
<Repos />
</Suspense>
</div>
)
}
22 changes: 22 additions & 0 deletions examples/suspense-global/pages/repos.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import Link from 'next/link'
import { ProjectsData } from './api/data'

import useSWR from 'swr'

const Repos = () => {
const { data } = useSWR<ProjectsData>('/api/data')

return (
<>
{data.map(project => (
<p key={project}>
<Link href="/[user]/[repo]" as={`/${project}`}>
{project}
</Link>
</p>
))}
</>
)
}

export default Repos
30 changes: 30 additions & 0 deletions examples/suspense-global/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"noImplicitAny": true,
"plugins": [
{
"name": "next"
}
],
"baseUrl": ".",
"paths": {
"~/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@
"lint": "eslint . --ext .ts,.tsx --cache",
"lint:fix": "pnpm lint --fix",
"coverage": "jest --coverage",
"test-typing": "tsc --noEmit -p test/type/tsconfig.json && tsc --noEmit -p test/tsconfig.json",
"test-typing": "tsc -p test/tsconfig.json && tsc -p test/type/tsconfig.json && tsc -p test/type/suspense/tsconfig.json",
"test": "jest",
"test:build": "jest --config jest.config.build.js",
"test:e2e": "playwright test",
Expand Down
11 changes: 9 additions & 2 deletions src/_internal/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { SWRGlobalConfig } from '../index'
import type * as revalidateEvents from './events'

export type GlobalState = [
Expand Down Expand Up @@ -33,7 +34,9 @@ export type ReactUsePromise<T = unknown, Error = unknown> = Promise<any> & {
export type BlockingData<
Data = any,
Options = SWROptions<Data>
> = Options extends undefined
> = SWRGlobalConfig extends { suspense: true }
? true
: Options extends undefined
? false
: Options extends { suspense: true }
? true
Expand Down Expand Up @@ -456,7 +459,11 @@ export type SWRConfiguration<
export type IsLoadingResponse<
Data = any,
Options = SWROptions<Data>
> = Options extends { suspense: true } ? false : boolean
> = SWRGlobalConfig extends { suspense: true }
? Options extends { suspense: true }
? false
: false
: boolean

type SWROptions<Data> = SWRConfiguration<Data, Error, Fetcher<Data, Key>>
type SWRConfigurationWithOptionalFallback<Options> =
Expand Down
6 changes: 6 additions & 0 deletions src/index/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ export { useSWRConfig } from '../_internal'
export { mutate } from '../_internal'
export { preload } from '../_internal'

// Config
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface SWRGlobalConfig {
// suspense: true
}

// Types
export type {
SWRConfiguration,
Expand Down
5 changes: 3 additions & 2 deletions test/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"strict": false,
"jsx": "react-jsx",
"baseUrl": "..",
Expand All @@ -10,8 +11,8 @@
"swr/immutable": ["./immutable/src/index.ts"],
"swr/mutation": ["./mutation/src/index.ts"],
"swr/_internal": ["./_internal/src/index.ts"],
"swr/subscription": ["subscription/src/index.ts"],
},
"swr/subscription": ["subscription/src/index.ts"]
}
},
"include": [".", "./jest-setup.ts"],
"exclude": ["./type"]
Expand Down
19 changes: 19 additions & 0 deletions test/type/suspense/helper-types.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { BlockingData } from 'swr/_internal'
import { expectType } from '../utils'

declare module 'swr' {
interface SWRGlobalConfig {
suspense: true
}
}

export function testDataCached() {
expectType<BlockingData<string, { fallbackData: string }>>(true)
expectType<BlockingData<any, { suspense: true }>>(true)
expectType<
BlockingData<string, { fallbackData?: string; revalidate: boolean }>
>(true)
expectType<BlockingData<false, { suspense: false; revalidate: boolean }>>(
true
)
}
13 changes: 13 additions & 0 deletions test/type/suspense/suspense.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import useSWR from 'swr'
import { expectType } from '../utils'

declare module 'swr' {
interface SWRGlobalConfig {
suspense: true
}
}

export function testSuspense() {
const { data } = useSWR('/api', (k: string) => Promise.resolve(k))
expectType<string>(data)
}
10 changes: 10 additions & 0 deletions test/type/suspense/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"strict": true,
"jsx": "react-jsx"
},
"include": ["./**/*.ts", "./**/*.tsx"],
"exclude": []
}
Loading
Loading
0