All files / context/favorites index.tsx

100% Statements 17/17
100% Branches 0/0
100% Functions 8/8
100% Lines 14/14

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                              21x       21x 75x         75x 2x     75x 2x     75x 71x 71x   71x 71x 71x       75x                
import { useEffect, createContext } from 'react';
 
import { events } from 'app';
import { usePersistedState } from 'hooks';
 
import { Entity, Events } from 'types';
 
type FavoritesContextData = {
  favorites: Entity[];
};
 
type FavoritesProviderProps = {
  children: React.ReactNode;
};
 
const FavoritesContext = createContext<FavoritesContextData>(
  {} as FavoritesContextData
);
 
const FavoritesProvider = ({ children }: FavoritesProviderProps) => {
  const [favorites, setFavorites] = usePersistedState<Entity[]>(
    'favorites',
    []
  );
 
  const handleAdd = (event: CustomEvent<Entity>) => {
    setFavorites(state => [...state, event.detail]);
  };
 
  const handleRemove = (event: CustomEvent<{ id: string }>) => {
    setFavorites(state => state.filter(item => item.id !== event.detail.id));
  };
 
  useEffect(() => {
    events.on(Events.ADD_FAVORITE, handleAdd);
    events.on(Events.REMOVE_FAVORITE, handleRemove);
 
    return () => {
      events.off(Events.ADD_FAVORITE, handleAdd);
      events.off(Events.REMOVE_FAVORITE, handleRemove);
    };
  }, []);
 
  return (
    <FavoritesContext.Provider value={{ favorites }}>
      {children}
    </FavoritesContext.Provider>
  );
};
 
export { FavoritesProvider, FavoritesContext };