Files
web2.0-frontend/src/hooks/useFetchEvents.ts
T
2021-05-16 02:01:36 +03:00

58 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, onlyNonPast, limit, offset,
auth, limit, offset,
} = options;
return {
url,
config: {
params: {
// since: onlyNonPast ? (new Date()).toISOString() : undefined,
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;