All files / context/search index.tsx

100% Statements 48/48
100% Branches 12/12
100% Functions 6/6
100% Lines 46/46

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123                                                    21x   21x 94x 94x   94x 94x   94x 94x   94x 12x 12x   12x   12x 12x   12x   9x   9x 9x   9x   9x 1x 1x     8x 8x   8x   8x   8x         5x   5x   3x     3x   3x     2x   2x       2x 2x   8x   8x       94x 71x   71x 71x       94x 71x 71x       94x                
import { useEffect, useRef, useState, createContext } from 'react';
import axios from 'axios';
 
import { events } from 'app';
import { Entities, Entity, Events } from 'types';
 
type Cache<T = any> = {
  [key: string]: T;
};
 
type MakeSearch = {
  entity: Entities;
  search: string;
};
 
type FetchDataArgs = CustomEvent<MakeSearch>;
 
type SearchContextData = {
  data: Entity[];
  isFetching: boolean;
};
 
type SearchProviderProps = {
  children: React.ReactNode;
};
 
const SearchContext = createContext<SearchContextData>({} as SearchContextData);
 
const SearchProvider = ({ children }: SearchProviderProps) => {
  const cacheRef = useRef<Cache>({});
  const abortRef = useRef<AbortController>();
 
  const entityRef = useRef<Entities>(Entities.CHARACTERS);
  const searchRef = useRef('');
 
  const [data, setData] = useState<Entity[]>([]);
  const [isFetching, setIsFetching] = useState(false);
 
  const fetchData = async (event: FetchDataArgs) => {
    const saveEntity = entityRef.current;
    const saveSearch = searchRef.current;
 
    const { entity = saveEntity, search = saveSearch } = event.detail;
 
    entityRef.current = entity;
    searchRef.current = search;
 
    if (!search) return;
 
    abortRef.current?.abort();
 
    const cache = cacheRef.current;
    const key = `${entity}-${search}`;
 
    const result = cache[key];
 
    if (result) {
      setData(result);
      return;
    }
 
    try {
      setIsFetching(true);
 
      const abortController = new AbortController();
 
      abortRef.current = abortController;
 
      const { data } = await axios.get<Entity[]>('/api/data', {
        params: { entity, search },
        signal: abortController.signal,
      });
 
      cacheRef.current[key] = data;
 
      setData(data);
    } catch (err) {
      console.error(err);
 
      const wasCanceled =
        err instanceof Object && err.constructor.name === 'Cancel';
 
      if (wasCanceled) return;
 
      const defaultErrorMessage =
        'An error has occurred, try again or come back soon';
 
      const error = axios.isAxiosError(err)
        ? err.response?.data.error
        : defaultErrorMessage;
 
      setData([]);
      events.search.error(error);
    } finally {
      setIsFetching(false);
 
      abortRef.current = undefined;
    }
  };
 
  useEffect(() => {
    events.on(Events.MAKE_SEARCH, fetchData);
 
    return () => {
      events.off(Events.MAKE_SEARCH, fetchData);
    };
  }, []);
 
  useEffect(() => {
    return () => {
      abortRef.current?.abort();
    };
  }, []);
 
  return (
    <SearchContext.Provider value={{ data, isFetching }}>
      {children}
    </SearchContext.Provider>
  );
};
 
export { SearchProvider, SearchContext };