UNPKG

1.28 kBPlain TextView Raw
1import { AtomFeed } from './AtomFeed';
2import { parseAtomFeed } from './Parser';
3import useSWR, { SWRConfiguration } from 'swr';
4
5export interface Response<Data> {
6 data?: Data;
7 error?: Error;
8 isValidating: boolean;
9}
10
11/**
12 * The React hook used for reading the Atom feed.
13 * @param feedURL The URL of the Atom feed
14 * @param options Options that are passed to `useSWR()` behind the scenes.
15 * More info: https://swr.vercel.app/docs/options#options
16 * @returns The decoded Atom feed or any errors seen along the way
17 */
18export function useAtomFeed(feedURL: string, options?: SWRConfiguration): Response<AtomFeed> {
19 const fetcher = (url: string) => fetch(url).then(res => res.text());
20 const { data, error, isValidating } = useSWR(feedURL, fetcher, options);
21
22 // if data is defined
23 if(data) {
24 // attempt to decode
25 try {
26 const decoded = parseAtomFeed(data);
27 // return a good decode
28 return {
29 data: decoded,
30 error,
31 isValidating
32 }
33 }
34 catch(parseError) {
35 // return a decode failure
36 return {
37 data: undefined,
38 error: parseError,
39 isValidating
40 }
41 }
42 }
43 else {
44 // data is undefined
45 return {
46 data: undefined,
47 error,
48 isValidating
49 }
50 }
51}