Files
web2.0-frontend/src/hooks/useFetchFeed.ts
T
2021-03-28 20:32:07 +03:00

50 lines
1.3 KiB
TypeScript

import { useRef } from "react";
import useSWR from "swr";
import isDeepEqual from "fast-deep-equal/react";
import axios, { AxiosRequestConfig } from "axios";
import Post from "@models/Feed";
import { getAuthHeader } from "@utils/auth";
import { URL, Options } from "@api/feedApi";
const feedFetcher = (url: string, config?: AxiosRequestConfig) => axios.get(url, config).then((res) => res.data);
const generateFetchParams = (id = "", options: Options = {}) => {
const url = `${URL}${id}`;
const { auth } = options;
return {
url,
config: {
headers: auth ? { Authorization: getAuthHeader() } : null,
},
};
};
interface FetchArguments {
initialData?: Post | Post[],
id?: string;
options?: Options
}
const useFetchFeed = ({
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], feedFetcher, { initialData });
return {
data: data?.results || data,
error,
};
};
export default useFetchFeed;