[5d6f37a] | 1 | import { useMemo } from 'react';
|
---|
| 2 | // types
|
---|
| 3 | import { Settings } from 'src/types/settings';
|
---|
| 4 | // db
|
---|
| 5 | import { collections, collectionFetcher as fetcher } from 'src/lib/firestore';
|
---|
| 6 | // swr
|
---|
| 7 | import useSWR from 'swr';
|
---|
| 8 |
|
---|
| 9 | export function useGetSettings() {
|
---|
| 10 | const collectionName = collections.settings;
|
---|
| 11 |
|
---|
| 12 | const { data, isLoading, error, isValidating } = useSWR(collectionName, fetcher<Settings>, {
|
---|
| 13 | revalidateOnFocus: false,
|
---|
| 14 | });
|
---|
| 15 |
|
---|
| 16 | const dataObject = transformArrayToObject(data);
|
---|
| 17 |
|
---|
| 18 | const memoizedValue = useMemo(
|
---|
| 19 | () => ({
|
---|
| 20 | settings: dataObject || null,
|
---|
| 21 | settingsLoading: isLoading,
|
---|
| 22 | settingsError: error,
|
---|
| 23 | settingsValidating: isValidating,
|
---|
| 24 | settingsEmpty: !isLoading && !dataObject,
|
---|
| 25 | }),
|
---|
| 26 | [dataObject, error, isLoading, isValidating]
|
---|
| 27 | );
|
---|
| 28 |
|
---|
| 29 | return memoizedValue;
|
---|
| 30 | }
|
---|
| 31 |
|
---|
| 32 | const transformArrayToObject = (data?: Settings[]): Settings | undefined => {
|
---|
| 33 | if (!data) return undefined;
|
---|
| 34 |
|
---|
| 35 | return data.reduce((accumulator: Settings, doc) => {
|
---|
| 36 | const { id, ...fields } = doc;
|
---|
| 37 | accumulator[id as keyof Settings] = fields;
|
---|
| 38 | return accumulator;
|
---|
| 39 | }, {} as Settings);
|
---|
| 40 | };
|
---|