Skip to content

Commit

Permalink
docs(userequest demos): add demos of useRequest
Browse files Browse the repository at this point in the history
  • Loading branch information
innocces committed Jul 11, 2021
1 parent 97f6d0d commit 909c3ca
Show file tree
Hide file tree
Showing 19 changed files with 409 additions and 2 deletions.
6 changes: 6 additions & 0 deletions packages/app/src/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ export default {
'pages/useRequest/polling/index',
'pages/useRequest/concurrent/index',
'pages/useRequest/ready/index',
'pages/useRequest/debounce/index',
'pages/useRequest/throttle/index',
'pages/useRequest/cacheKey/index',
'pages/useRequest/preload/index',
'pages/useRequest/refreshOnWindowFocus/index',
// 'pages/useRequest/mutate/index',
'pages/useNetworkType/index',
'pages/useOnline/index',
],
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/app.less
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ page {

&__content {
padding: 0 20px;
position: relative;

&.no-padding {
padding: 0;
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/pages/useRequest/cacheKey/index.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
navigationBarTitleText: 'useRequest 缓存 & SWR',
};
59 changes: 59 additions & 0 deletions packages/app/src/pages/useRequest/cacheKey/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* desc: 通过 `options.fetchKey` ,可以将请求进行分类,每一类的请求都有独立的状态,你可以在 `fetches` 中找到所有的请求。
*/
import React, { useState } from 'react';
import { useRequest } from 'taro-hooks';
import Mock from 'mockjs';

import { AtButton } from 'taro-ui';
import { View } from '@tarojs/components';
import DocPage from '@components/DocPage';

async function getArticle(): Promise<{ data: string; time: number }> {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
data: Mock.mock('@cparagraph(10, 20)'),
time: new Date().getTime(),
});
}, 1000);
});
}

const Article = () => {
const { data, loading } = useRequest(getArticle, {
cacheKey: 'article',
});
if (!data && loading) {
return <View>loading</View>;
}
return (
<>
<View>Latest request time: {data?.time}</View>
<View>{data?.data}</View>
</>
);
};

const CacheKeyRequest = () => {
const [state, setState] = useState<boolean>(false);

return (
<DocPage title="useRequest 请求" panelTitle="缓存 & SWR">
<View>
You can click the button multiple times, the article component will show
the cached data first.
</View>
<AtButton
type="primary"
onClick={() => setState(!state)}
customStyle={{ marginTop: '10px' }}
>
show/hidden
</AtButton>
{state && <Article />}
</DocPage>
);
};

export default CacheKeyRequest;
2 changes: 2 additions & 0 deletions packages/app/src/pages/useRequest/concurrent/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { AtMessage, AtButton } from 'taro-ui';
import { View } from '@tarojs/components';
import DocPage from '@components/DocPage';

import 'taro-ui/dist/style/components/icon.scss';

type Result = { success: boolean };

export function deleteUser(userId: string): Promise<Result> {
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/pages/useRequest/debounce/index.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
navigationBarTitleText: 'useRequest 防抖',
};
53 changes: 53 additions & 0 deletions packages/app/src/pages/useRequest/debounce/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* desc: 通过设置 `options.debounceInterval` ,则进入防抖模式。此时如果频繁触发 `run` ,则会以防抖策略进行请求。
*/
import React, { useEffect, useState } from 'react';
import { useRequest } from 'taro-hooks';
import Mock from 'mockjs';

import { AtInput, AtList, AtListItem } from 'taro-ui';
import { View } from '@tarojs/components';
import DocPage from '@components/DocPage';

async function getEmail(search: string): Promise<string[]> {
console.log(search);
return new Promise((resolve) => {
setTimeout(() => {
resolve(Mock.mock({ 'data|5': ['@email()'] }).data);
}, 300);
});
}

const DebounceRequest = () => {
const { data, loading, run } = useRequest(getEmail, {
debounceInterval: 500,
manual: true,
});

const [value, setValue] = useState<string>();

useEffect(() => {
value && run(value);
}, [value, run]);

return (
<DocPage title="useRequest 请求" panelTitle="防抖">
<View>Enter quickly to see the effect</View>
<AtInput
name="email"
value={value}
onChange={(e) => setValue(e as string)}
placeholder="Select Emails"
/>
{loading ? (
<View>loading...</View>
) : (
<AtList>
{data && data.map((i: string) => <AtListItem key={i} title={i} />)}
</AtList>
)}
</DocPage>
);
};

export default DebounceRequest;
30 changes: 30 additions & 0 deletions packages/app/src/pages/useRequest/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,36 @@ const list: IListItem[] = [
note: '只有当 options.ready 变为 true 时, 才会发起请求,基于该特性可以实现串行请求,依赖请求等。',
route: 'ready',
},
{
title: '防抖',
note: '通过设置 options.debounceInterval ,则进入防抖模式。此时如果频繁触发 run ,则会以防抖策略进行请求。',
route: 'debounce',
},
{
title: '节流',
note: '通过设置 options.throttleInterval ,则进入节流模式。此时如果频繁触发 run ,则会以节流策略进行请求。',
route: 'throttle',
},
{
title: '缓存 & SWR',
note: '如果设置了 options.cacheKey , useRequest 会将当前请求结束数据缓存起来。下次组件初始化时,如果有缓存数据,我们会优先返回缓存数据,然后在背后发送新请求,也就是 SWR 的能力。你可以通过 cacheTime 设置缓存数据回收时间,也可以通过 staleTime 设置数据保持新鲜时间。',
route: 'cacheKey',
},
{
title: '预加载',
note: '同一个 cacheKey 的请求,是全局共享的,也就是你可以提前加载数据。利用该特性,可以很方便的实现预加载。',
route: 'preload',
},
{
title: '屏幕聚焦重新请求',
note: '如果你设置了 options.refreshOnWindowFocus = true ,则在浏览器窗口 refocus 和 revisible 时,会重新发起请求。你可以通过设置 options.focusTimespan 来设置请求间隔,默认为 5000ms 。',
route: 'refreshOnWindowFocus',
},
{
title: '突变',
note: '你可以通过 mutate ,直接修改 data 。 mutate 函数参数可以为 newData 或 (oldData)=> newData 。',
route: 'mutate',
},
];

export default () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/pages/useRequest/manual/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import Taro from '@tarojs/taro';
import { AtMessage, AtInput, AtButton } from 'taro-ui';
import DocPage from '@components/DocPage';

import 'taro-ui/dist/style/components/icon.scss';

type Result = { success: boolean };

function changeUsername(username: string): Promise<Result> {
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/pages/useRequest/mutate/index.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
navigationBarTitleText: 'useRequest 突变',
};
46 changes: 46 additions & 0 deletions packages/app/src/pages/useRequest/mutate/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* desc: 你可以通过 `mutate` ,直接修改 `data` 。 `mutate` 函数参数可以为 `newData` 或 `(oldData)=> newData` 。
*/
import React, { useState } from 'react';
import { useRequest } from 'taro-hooks';
import Mock from 'mockjs';

import { AtInput, AtButton } from 'taro-ui';
import { View } from '@tarojs/components';
import DocPage from '@components/DocPage';

import 'taro-ui/dist/style/components/icon.scss';

function getUsername(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Mock.mock('@name()'));
}, 1000);
});
}

const MutateRequest = () => {
const [state, setState] = useState('');
const { data, mutate, loading } = useRequest(getUsername, {
onSuccess: (result: string) => {
setState(result);
},
});

return (
<DocPage title="useRequest 请求" panelTitle="突变">
<View>username: {data}</View>
<AtInput
name="username"
onChange={(e) => setState(e as string)}
value={state}
placeholder="Please enter username"
/>
<AtButton type="primary" loading={loading} onClick={() => mutate(state)}>
{loading ? 'loading' : 'Edit'}
</AtButton>
</DocPage>
);
};

export default MutateRequest;
3 changes: 3 additions & 0 deletions packages/app/src/pages/useRequest/preload/index.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
navigationBarTitleText: 'useRequest 预加载',
};
66 changes: 66 additions & 0 deletions packages/app/src/pages/useRequest/preload/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
* desc: 同一个 `cacheKey` 的请求,是全局共享的,也就是你可以提前加载数据。利用该特性,可以很方便的实现预加载。
*/
import React, { useEffect, useState } from 'react';
import { useRequest } from 'taro-hooks';
import Mock from 'mockjs';

import { AtButton } from 'taro-ui';
import { View } from '@tarojs/components';
import DocPage from '@components/DocPage';

async function getArticle(): Promise<{ data: string; time: number }> {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
data: Mock.mock('@cparagraph(10, 20)'),
time: new Date().getTime(),
});
}, 1000);
});
}

const Article = () => {
const { data, loading } = useRequest(getArticle, {
cacheKey: 'article',
});
if (!data && loading) {
return <View>loading</View>;
}
return (
<>
<View>Latest request time: {data?.time}</View>
<View>{data?.data}</View>
</>
);
};

const PreloadRequest = () => {
const [state, setState] = useState<boolean>(false);
const { run } = useRequest(getArticle, {
cacheKey: 'article',
manual: true,
});

useEffect(() => {
if (!state) {
run();
}
}, [state, run]);

return (
<DocPage title="useRequest 请求" panelTitle="预加载">
<View>When the article hidden, the article data is preloaded.</View>
<AtButton
type="primary"
onClick={() => setState(!state)}
customStyle={{ marginTop: '10px' }}
>
show/hidden
</AtButton>
{state && <Article />}
</DocPage>
);
};

export default PreloadRequest;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
navigationBarTitleText: 'useRequest 屏幕聚焦重新请求',
};
43 changes: 43 additions & 0 deletions packages/app/src/pages/useRequest/refreshOnWindowFocus/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* desc: 只有当 `options.ready` 变为 true 时, 才会发起请求,基于该特性可以实现串行请求,依赖请求等。
*/
import React from 'react';
import { useRequest } from 'taro-hooks';
import Mock from 'mockjs';

import { View } from '@tarojs/components';
import { AtActivityIndicator } from 'taro-ui';
import DocPage from '@components/DocPage';

import 'taro-ui/dist/style/components/loading.scss';

function getUsername(): Promise<string> {
const userInfo = Mock.mock('@name()');
return new Promise((resolve) => {
setTimeout(() => {
resolve(userInfo);
}, 1000);
});
}

const RefreshOnWindowFocusRequest = () => {
const { data, loading } = useRequest(getUsername, {
refreshOnWindowFocus: true,
});

return (
<DocPage title="useRequest 请求" panelTitle="屏幕聚焦重新请求">
<View>
You can try to click elsewhere and click back to try. (Or hide the page
and show it again)
</View>
<AtActivityIndicator
mode="center"
isOpened={loading}
></AtActivityIndicator>
<View>Username: {data}</View>
</DocPage>
);
};

export default RefreshOnWindowFocusRequest;
3 changes: 3 additions & 0 deletions packages/app/src/pages/useRequest/throttle/index.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
navigationBarTitleText: 'useRequest 节流',
};
Loading

0 comments on commit 909c3ca

Please sign in to comment.