Skip to content

Commit

Permalink
refactor: recoil 네이밍 변경 및 데이터 구조 변경에 따른 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
nangkyeonglim committed May 20, 2023
1 parent 4d0209d commit 0527994
Showing 1 changed file with 31 additions and 32 deletions.
63 changes: 31 additions & 32 deletions src/stores/cartItemsStore.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,41 @@
import { AtomEffect, atom, selector, selectorFamily } from 'recoil';
import type { CartItems } from '../types/index.ts';
import { getLocalStorage, setLocalStorage } from '../utils/localStorage.ts';
import { LOCAL_STORAGE_KEY } from '../constants/index.ts';

const cartItemsLocalStorageEffect: <T>(key: string) => AtomEffect<T> =
(key: string) =>
({ setSelf, onSet }) => {
const savedValue = getLocalStorage(key, null);

if (savedValue) setSelf(savedValue);

onSet((newValue) => {
setLocalStorage(key, newValue);
});
};

export const cartItemsAtom = atom<CartItems>({
key: 'cartItemsAtom',
default: {},
effects: [cartItemsLocalStorageEffect<CartItems>(LOCAL_STORAGE_KEY.CART_ITEMS)],
import { atom, selector, selectorFamily } from 'recoil';
import type { CartItem } from '../types/index.ts';

export const cartListAtom = atom<CartItem[]>({
key: 'cartListAtom',
default: [],
});

export const cartItemsQuantitySelector = selector({
key: 'cartItemsQuantitySelector',
get: ({ get }) => {
const cartItems = get(cartItemsAtom);
export const cartItemQuantitySelector = selectorFamily({
key: 'cartItemQuantitySelector',
get:
(productId: number) =>
({ get }) => {
const cartList = get(cartListAtom);
const targetItem = cartList.find((item) => item.product.id === productId);

return Object.keys(cartItems).length;
},
return targetItem ? targetItem.quantity : 0;
},
});

export const productQuantitySelector = selectorFamily({
key: 'productQuantitySelector',
export const cartItemIdSelector = selectorFamily({
key: 'cartItemIdSelector',
get:
(itemId: number) =>
(productId: number) =>
({ get }) => {
const cartItems = get(cartItemsAtom);
const cartList = get(cartListAtom);

return cartItems[itemId]?.quantity ?? 0;
const targetItem = cartList.find((item) => item.product.id === productId);

return targetItem ? targetItem.id : null;
},
});

export const cartCountSelector = selector({
key: 'cartCountSelector',
get: ({ get }) => {
const cartList = get(cartListAtom);

return cartList.length;
},
});

0 comments on commit 0527994

Please sign in to comment.