2023-02-22 21:30:48 -05:00
|
|
|
/* eslint-disable react-hooks/rules-of-hooks */
|
2023-02-07 16:22:35 -05:00
|
|
|
import axios from 'axios';
|
|
|
|
|
import useSWR from 'swr';
|
|
|
|
|
import useSWRMutation from 'swr/mutation';
|
|
|
|
|
|
2023-03-18 14:28:10 -04:00
|
|
|
const fetcher = (url) => fetch(url, { credentials: 'include' }).then((res) => res.json());
|
|
|
|
|
const axiosFetcher = async (url, params) => {
|
|
|
|
|
console.log(params, 'params');
|
|
|
|
|
return axios.get(url, params);
|
|
|
|
|
};
|
2023-02-07 16:22:35 -05:00
|
|
|
|
|
|
|
|
const postRequest = async (url, { arg }) => {
|
2023-03-14 01:24:43 +08:00
|
|
|
return await axios.post(url, { withCredentials: true, arg });
|
2023-02-07 16:22:35 -05:00
|
|
|
};
|
|
|
|
|
|
2023-03-18 17:49:24 -04:00
|
|
|
export const searchFetcher = async (pre, q, pageNumber, callback) => {
|
|
|
|
|
pre();
|
|
|
|
|
const { data } = await axios.get(`/api/search?q=${q}&pageNumber=${pageNumber}`);
|
|
|
|
|
console.log('search data', data);
|
|
|
|
|
callback(data);
|
|
|
|
|
};
|
|
|
|
|
|
2023-03-15 04:05:14 +08:00
|
|
|
export const swr = (path, successCallback, options) => {
|
2023-03-18 14:28:10 -04:00
|
|
|
const _options = { ...options };
|
2023-02-13 23:14:35 -05:00
|
|
|
|
|
|
|
|
if (successCallback) {
|
2023-03-15 04:05:14 +08:00
|
|
|
_options.onSuccess = successCallback;
|
2023-02-13 23:14:35 -05:00
|
|
|
}
|
|
|
|
|
|
2023-03-15 04:05:14 +08:00
|
|
|
return useSWR(path, fetcher, _options);
|
2023-03-18 14:28:10 -04:00
|
|
|
};
|
2023-02-07 16:22:35 -05:00
|
|
|
|
|
|
|
|
export default function manualSWR(path, type, successCallback) {
|
2023-02-07 19:07:48 -05:00
|
|
|
const options = {};
|
|
|
|
|
|
|
|
|
|
if (successCallback) {
|
|
|
|
|
options.onSuccess = successCallback;
|
|
|
|
|
}
|
2023-02-07 16:22:35 -05:00
|
|
|
const fetchFunction = type === 'get' ? fetcher : postRequest;
|
2023-02-07 19:07:48 -05:00
|
|
|
return useSWRMutation(path, fetchFunction, options);
|
2023-03-04 17:39:06 -05:00
|
|
|
}
|
2023-03-18 14:28:10 -04:00
|
|
|
|
|
|
|
|
export function useManualSWR({ path, params, type, onSuccess }) {
|
|
|
|
|
const options = {};
|
|
|
|
|
|
|
|
|
|
if (onSuccess) {
|
|
|
|
|
options.onSuccess = onSuccess;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log(params, 'params');
|
|
|
|
|
|
|
|
|
|
const fetchFunction = type === 'get' ? _.partialRight(axiosFetcher, params) : postRequest;
|
|
|
|
|
return useSWRMutation(path, fetchFunction, options);
|
|
|
|
|
}
|