All files / src/hooks useSns.ts

100% Statements 28/28
100% Branches 5/5
100% Functions 5/5
100% Lines 27/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 595x   5x 5x 5x                     5x 2x 2x   1x 1x 1x 1x 1x 1x 1x   1x   2x                 1x     5x 4x   4x 4x 2x 2x 2x 1x   1x         4x    
import React from 'react';
 
import { endpoints } from '@/constants';
import { getApiClient, GoogleSheetsApiResponse } from '@/lib';
import { handleError } from '@/utils/errors';
 
export type Sns = {
  id: number;
  'title_ja-JP': string;
  'title_en-US': string;
  favicon: string;
  url: string;
  visible: boolean;
};
 
const fetchData = async () => {
  const client = getApiClient();
  const [snsResponse] = await Promise.all([client.get<GoogleSheetsApiResponse>(endpoints.getSns)]);
 
  const sns = snsResponse.data.values[0];
  const sns_id = sns.indexOf('id');
  const sns_titleJaJp = sns.indexOf('title_ja-JP');
  const sns_titleEnUs = sns.indexOf('title_en-US');
  const sns_favicon = sns.indexOf('favicon');
  const sns_url = sns.indexOf('url');
  const sns_visible = sns.indexOf('visible');
 
  const buffer = snsResponse.data.values.slice(1, snsResponse.data.values.length).map(
    (row) =>
      ({
        id: Number(row[sns_id]),
        'title_ja-JP': row[sns_titleJaJp],
        'title_en-US': row[sns_titleEnUs],
        favicon: row[sns_favicon],
        url: row[sns_url],
        visible: row[sns_visible]?.toLowerCase() === 'true' ? true : false,
      } as Sns)
  );
  return buffer;
};
 
export const useSns = (ready: boolean) => {
  const [cache, setCache] = React.useState<Sns[]>();
 
  React.useEffect(() => {
    if (ready && !cache)
      (async () => {
        try {
          const data = await fetchData();
          setCache(data);
        } catch (e) {
          handleError(e);
        }
      })();
  }, [ready, cache]);
 
  return cache;
};