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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: useRequest support params #2684

Open
wants to merge 3 commits into
base: master
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
44 changes: 44 additions & 0 deletions packages/hooks/src/useRequest/doc/basic/demo/defaultParams.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useRequest } from 'ahooks';
import Mock from 'mockjs';
import React, { useState } from 'react';

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

export default () => {
const [state, setState] = useState('');

// get username
const {
data: username,
run,
params,
} = useRequest(getUsername, {
defaultParams: ['1'],
});

const onChange = () => {
run(state);
};

return (
<div>
<input
onChange={(e) => setState(e.target.value)}
value={state}
placeholder="Please enter userId"
style={{ width: 240, marginRight: 16 }}
/>
<button type="button" onClick={onChange}>
GetUserName
</button>
<p style={{ marginTop: 8 }}>UserId: {params[0]}</p>
<p>Username: {username}</p>
</div>
);
};
14 changes: 6 additions & 8 deletions packages/hooks/src/useRequest/doc/basic/demo/params.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
import { useRequest } from 'ahooks';
import Mock from 'mockjs';
import React, { useState } from 'react';
import { useRequest } from "ahooks";
import Mock from "mockjs";
import React, { useState } from "react";

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

export default () => {
const [state, setState] = useState('');
const [state, setState] = useState("");

// get username
const {
data: username,
run,
params,
} = useRequest(getUsername, {
defaultParams: ['1'],
});
} = useRequest(getUsername, { params: [state] });

const onChange = () => {
run(state);
Expand Down
14 changes: 11 additions & 3 deletions packages/hooks/src/useRequest/src/plugins/useAutoRunPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@ import type { Plugin } from '../types';
// support refreshDeps & ready
const useAutoRunPlugin: Plugin<any, any[]> = (
fetchInstance,
{ manual, ready = true, defaultParams = [], refreshDeps = [], refreshDepsAction },
{ manual, ready = true, defaultParams = [], params = [], refreshDeps = [], refreshDepsAction },
) => {
const hasAutoRun = useRef(false);
hasAutoRun.current = false;

useUpdateEffect(() => {
if (!manual && ready) {
hasAutoRun.current = true;
fetchInstance.run(...defaultParams);
if (params.length > 0) {
fetchInstance.run(...params);
} else {
fetchInstance.run(...defaultParams);
}
}
}, [ready]);

Expand All @@ -26,7 +30,11 @@ const useAutoRunPlugin: Plugin<any, any[]> = (
if (refreshDepsAction) {
refreshDepsAction();
} else {
fetchInstance.refresh();
if (params.length > 0) {
fetchInstance.run(...params);
} else {
fetchInstance.refresh();
}
}
}
}, [...refreshDeps]);
Expand Down
2 changes: 2 additions & 0 deletions packages/hooks/src/useRequest/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export interface Options<TData, TParams extends any[]> {
onFinally?: (params: TParams, data?: TData, e?: Error) => void;

defaultParams?: TParams;

params?: TParams;

// refreshDeps
refreshDeps?: DependencyList;
Expand Down
37 changes: 23 additions & 14 deletions packages/hooks/src/useRequest/src/useRequestImplement.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
import useCreation from '../../useCreation';
import useLatest from '../../useLatest';
import useMemoizedFn from '../../useMemoizedFn';
import useMount from '../../useMount';
import useUnmount from '../../useUnmount';
import useUpdate from '../../useUpdate';
import isDev from '../../utils/isDev';
import useCreation from "../../useCreation";
import useLatest from "../../useLatest";
import useMemoizedFn from "../../useMemoizedFn";
import useMount from "../../useMount";
import useUnmount from "../../useUnmount";
import useUpdate from "../../useUpdate";
import isDev from "../../utils/isDev";

import Fetch from './Fetch';
import type { Options, Plugin, Result, Service } from './types';
import Fetch from "./Fetch";
import type { Options, Plugin, Result, Service } from "./types";

function useRequestImplement<TData, TParams extends any[]>(
service: Service<TData, TParams>,
options: Options<TData, TParams> = {},
plugins: Plugin<TData, TParams>[] = [],
plugins: Plugin<TData, TParams>[] = []
) {
const { manual = false, ready = true, ...rest } = options;

if (isDev) {
if (options.defaultParams && !Array.isArray(options.defaultParams)) {
console.warn(`expected defaultParams is array, got ${typeof options.defaultParams}`);
console.warn(
`expected defaultParams is array, got ${typeof options.defaultParams}`
);
}
if (options.params && !Array.isArray(options.params)) {
console.warn(`expected params is array, got ${typeof options.params}`);
}
}

Expand All @@ -33,18 +38,22 @@ function useRequestImplement<TData, TParams extends any[]>(
const update = useUpdate();

const fetchInstance = useCreation(() => {
const initState = plugins.map((p) => p?.onInit?.(fetchOptions)).filter(Boolean);
const initState = plugins
.map((p) => p?.onInit?.(fetchOptions))
.filter(Boolean);

return new Fetch<TData, TParams>(
serviceRef,
fetchOptions,
update,
Object.assign({}, ...initState),
Object.assign({}, ...initState)
);
}, []);
fetchInstance.options = fetchOptions;
// run all plugins hooks
fetchInstance.pluginImpls = plugins.map((p) => p(fetchInstance, fetchOptions));
fetchInstance.pluginImpls = plugins.map((p) =>
p(fetchInstance, fetchOptions)
);

useMount(() => {
if (!manual && ready) {
Expand Down