Skip to content
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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(example): add xior and xior-typescript example #2917

Open
wants to merge 1 commit 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions examples/xior-typescript/README.md
@@ -0,0 +1,30 @@
# Xior TypeScript

## 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/xior-typescript)

## How to Use

Download the example:

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

Install it and run:

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

## The Idea behind the Example

Show how to use the basic xior along with TypeScript to type both the request object and the data received from SWR.
66 changes: 66 additions & 0 deletions examples/xior-typescript/libs/useRequest.ts
@@ -0,0 +1,66 @@
import useSWR, { SWRConfiguration, SWRResponse } from 'swr'
import axios, {
XiorRequestConfig as AxiosRequestConfig,
XiorResponse as AxiosResponse,
XiorError as AxiosError
} from 'xior'

export type GetRequest = AxiosRequestConfig | null

interface Return<Data, Error>
extends Pick<
SWRResponse<AxiosResponse<Data>, AxiosError>,
'isValidating' | 'error' | 'mutate'
> {
data: Data | undefined
response: AxiosResponse<Data> | undefined
}

export interface Config<Data = unknown, Error = unknown>
extends Omit<
SWRConfiguration<AxiosResponse<Data>, AxiosError>,
'fallbackData'
> {
fallbackData?: Data
}

export default function useRequest<Data = unknown, Error = unknown>(
request: GetRequest,
{ fallbackData, ...config }: Config<Data, Error> = {}
): Return<Data, Error> {
const {
data: response,
error,
isValidating,
mutate
} = useSWR<AxiosResponse<Data>, AxiosError>(
request,
/**
* NOTE: Typescript thinks `request` can be `null` here, but the fetcher
* function is actually only called by `useSWR` when it isn't.
*/
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
() => axios.request<Data>(request!),
{
...config,
fallbackData:
fallbackData &&
({
status: 200,
statusText: 'InitialData',
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
config: request!,
headers: {},
data: fallbackData
} as AxiosResponse<Data>)
}
)

return {
data: response && response.data,
response,
error,
isValidating,
mutate
}
}
5 changes: 5 additions & 0 deletions examples/xior-typescript/next-env.d.ts
@@ -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/basic-features/typescript for more information.
23 changes: 23 additions & 0 deletions examples/xior-typescript/package.json
@@ -0,0 +1,23 @@
{
"name": "xior-typescript",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"xior": "^0.2.4",
"next": "latest",
"react": "latest",
"react-dom": "latest",
"swr": "latest"
},
"scripts": {
"dev": "next",
"start": "next start",
"build": "next build"
},
"devDependencies": {
"@types/node": "16.7.2",
"@types/react": "17.0.19",
"typescript": "4.3.5"
}
}
34 changes: 34 additions & 0 deletions examples/xior-typescript/pages/[user]/[repo].tsx
@@ -0,0 +1,34 @@
import Link from 'next/link'

import useRequest from '../../libs/useRequest'

export default function Repo() {
const id =
typeof window !== 'undefined' ? window.location.pathname.slice(1) : ''
const { data } = useRequest<{
forks_count: number
stargazers_count: number
watchers: number
}>({
url: '/api/data',
params: { id }
})

return (
<div style={{ textAlign: 'center' }}>
<h1>{id}</h1>
{data ? (
<div>
<p>forks: {data.forks_count}</p>
<p>stars: {data.stargazers_count}</p>
<p>watchers: {data.watchers}</p>
</div>
) : (
'loading...'
)}
<br />
<br />
<Link href="/">Back</Link>
</div>
)
}
28 changes: 28 additions & 0 deletions examples/xior-typescript/pages/api/data.ts
@@ -0,0 +1,28 @@
import { NextApiRequest, NextApiResponse } from 'next'
import axios from 'xior'

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

export default function api(req: NextApiRequest, res: NextApiResponse) {
if (req.query.id) {
// a slow endpoint for getting repo data
axios
.request(`https://api.github.com/repos/${req.query.id}`)
.then(response => response.data)
.then(data => {
setTimeout(() => {
res.json(data)
}, 2000)
})

return
}
setTimeout(() => {
res.json(projects)
}, 2000)
}
26 changes: 26 additions & 0 deletions examples/xior-typescript/pages/index.tsx
@@ -0,0 +1,26 @@
import Link from 'next/link'

import useRequest from '../libs/useRequest'

export default function Index() {
const { data } = useRequest<string[]>({
url: '/api/data'
})

return (
<div style={{ textAlign: 'center' }}>
<h1>Trending Projects</h1>
<div>
{data
? data.map(project => (
<p key={project}>
<Link href="/[user]/[repo]" as={`/${project}`}>
{project}
</Link>
</p>
))
: 'loading...'}
</div>
</div>
)
}
29 changes: 29 additions & 0 deletions examples/xior-typescript/tsconfig.json
@@ -0,0 +1,29 @@
{
"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"
},
"exclude": [
"node_modules"
],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
]
}
30 changes: 30 additions & 0 deletions examples/xior/README.md
@@ -0,0 +1,30 @@
# Xior

## 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/xior)

## How to Use

Download the example:

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

Install it and run:

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

## The Idea behind the Example

Show a basic usage of SWR fetching using xior and a request object.
18 changes: 18 additions & 0 deletions examples/xior/libs/useRequest.js
@@ -0,0 +1,18 @@
import useSWR from 'swr'
import axios from 'xior'

export default function useRequest(request, { fallbackData, ...config } = {}) {
return useSWR(
request,
() => axios.request(request || {}).then(response => response.data),
{
...config,
fallbackData: fallbackData && {
status: 200,
statusText: 'InitialData',
headers: {},
data: fallbackData
}
}
)
}
18 changes: 18 additions & 0 deletions examples/xior/package.json
@@ -0,0 +1,18 @@
{
"name": "xior-example",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"xior": "^0.2.4",
"next": "latest",
"react": "latest",
"react-dom": "latest",
"swr": "latest"
},
"scripts": {
"dev": "next",
"start": "next start",
"build": "next build"
}
}
38 changes: 38 additions & 0 deletions examples/xior/pages/[user]/[repo].js
@@ -0,0 +1,38 @@
import Link from 'next/link'

import useRequest from '../../libs/useRequest'

export default function Repo() {
const id =
typeof window !== 'undefined' ? window.location.pathname.slice(1) : ''
const { data } = useRequest(
id
? {
url: '/api/data',
params: {
id
}
}
: null
)

return (
<div style={{ textAlign: 'center' }}>
<h1>{id}</h1>
{data ? (
<div>
<p>forks: {data.forks_count}</p>
<p>stars: {data.stargazers_count}</p>
<p>watchers: {data.watchers}</p>
</div>
) : (
'loading...'
)}
<br />
<br />
<Link href="/">
Back
</Link>
</div>
)
}
22 changes: 22 additions & 0 deletions examples/xior/pages/api/data.js
@@ -0,0 +1,22 @@
import axios from 'xior'

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

export default function api(req, res) {
if (req.query.id) {
// a slow endpoint for getting repo data
axios.request(`https://api.github.com/repos/${req.query.id}`)
.then(resp => resp.data)
.then(data => {
setTimeout(() => {
res.json(data)
}, 2000)
})
return
}
setTimeout(() => {
res.json(projects)
}, 2000)
}