57 lines
1.4 KiB
TypeScript
57 lines
1.4 KiB
TypeScript
import { useRef } from "react";
|
|
import useSWR from "swr";
|
|
import isDeepEqual from "fast-deep-equal/react";
|
|
import axios, { AxiosRequestConfig } from "axios";
|
|
import Event from "@models/Event";
|
|
import { getAuthHeader } from "@utils/auth";
|
|
import { URL, Options } from "@api/eventApi";
|
|
|
|
const fetcher = (url: string, config: AxiosRequestConfig) => axios.get(url, config).then((res) => res.data);
|
|
|
|
const generateFetchParams = (id = "", options: Options = {}) => {
|
|
const url = `${URL}${id}`;
|
|
const {
|
|
auth, since, limit, offset,
|
|
} = options;
|
|
|
|
return {
|
|
url,
|
|
config: {
|
|
params: {
|
|
since,
|
|
limit,
|
|
offset,
|
|
},
|
|
headers: auth ? { Authorization: getAuthHeader() } : null,
|
|
},
|
|
};
|
|
};
|
|
|
|
interface FetchArguments {
|
|
initialData?: Event | Event[],
|
|
id?: string;
|
|
options?: Options
|
|
}
|
|
|
|
const useFetchEvents = ({
|
|
initialData,
|
|
id = "",
|
|
options = {},
|
|
}: FetchArguments) => {
|
|
const { url, config } = generateFetchParams(id, options);
|
|
|
|
// Use ref, since config dependency is non-primitive => without this we have infinite fetch loop
|
|
const configRef = useRef(config);
|
|
if (!isDeepEqual(configRef.current, config)) {
|
|
configRef.current = config;
|
|
}
|
|
|
|
const { data, error } = useSWR([url, configRef.current], fetcher, { initialData });
|
|
return {
|
|
data: data?.results || data,
|
|
error,
|
|
};
|
|
};
|
|
|
|
export default useFetchEvents;
|