SWRConfig中处理不同方法的共享获取器



我有一个带有获取器的SWRConfig。我做了一些钩子:

function useData() {
const { data, mutate, error } = useRequest('data');
return {
data: data,
isLoading: !error && !data,
isError: error,
mutate,
};
}

userrequest是这样的:

export const useRequest = (path: string) => {
if (!path) {
throw new Error('Path is required');
}
const url = `${apiRoute}/api/${path}`;
const { data, mutate, error } = useSWR(url);
return { data, mutate, error };
};

所以在我的页面中,我导入我的钩子来获取数据和改变。

const { mutate, data } = usePayments();

是否有任何方法来处理GET和POST使用相同的获取器添加在配置中?

你可以向fetcher函数传递任意数量的参数

这在文档参数->多个参数。

您可以使用它将请求类型传递给获取器,并确定您是需要post还是get(或任何其他动词)。

enum RequestType {
GET,
POST
}
const fetcher = (url: string, type: RequestType) => {
console.log(url)
console.log(type)
switch (type) {
case RequestType.GET:
// Do a get;
break;
case RequestType.POST:
// Do a post
break;
}
}
export const useRequest = (path: string, type: RequestType = RequestType.GET) => {
if (!path) {
throw new Error('Path is required');
}

const url = `${apiRoute}/api/${path}`;

// First parameter is used to uniquely identify the request being made.
// This could just be a string, but it can also be an array of parameters
// that are needed to make the request (note that if any of the values 
// in the array fail a reference comparison the request will be triggered again).
// The values in the array will be provided to the fetcher function as parameters
// in the same order as they appear in the array (in this case URL followed by type).
// The second parameter is just assigning a non-default fetcher for this request,
// this is not needed if you have a single global fetcher that can meet your needs.
const { data, mutate, error } = useSWR([url, type], fetcher);

return { data, mutate, error };
};

最新更新