첫 번째로 사용한 방법
두 번째로 사용한 방법
예시 코드
//filter.store.js
const useFilterStore = create((set, get) => ({
typeFilters: [],
priceFilter: {},
addPriceFilter: (filter) => {
const prevFilters = get().typeFilters;
set({
typeFilters: [...prevFilters, filter]
});
},
delPriceFilter: (filter) => {
const deletedFilter = get().typeFilters.filter((prevFilter) => {
return prevFilter.name !== filter.name;
});
set({
typeFilters: deletedFilter
});
},
setPriceFilter: (filter) => {
set({
priceFilter: filter
});
}
}));
export default useFilterStore;
//Filter.jsx
function Filter() {
const { addPriceFilter, delPriceFilter, setPriceFilter } = useFilterStore(
useShallow((state) => ({
addPriceFilter: state.addPriceFilter,
delPriceFilter: state.delPriceFilter,
setPriceFilter: state.setPriceFilter
}))
);
const handleType = ({ target }) => {
const newFilter = { property: 'indutyNm', name: target.value };
if (target.checked) {
delPriceFilter(newFilter);
} else {
addPriceFilter(newFilter);
}
};
const handlePrice = ({ target }) => {
const newFilter = { property: 'priceRange', name: target.value };
if (target.checked) {
setPriceFilter(newFilter);
} else {
setPriceFilter({});
}
};
return(
...
)
}
//StoresMap.jsx
function StoresMap() {
const { jejuStores } = useFilteredJejuStore(
useShallow((state) => ({
jejuStores: state.jejuStores
}))
);
const [filteredStores, setFilteredStores] = useState(jejuStores);
const { typeFilters, priceFilter } = useFilterStore(
useShallow((state) => ({
typeFilters: state.typeFilters,
priceFilter: state.priceFilter
}))
);
useEffect(() => {
setFilteredStores(jejuStores);
if (typeFilters.length > 0) {
typeFilters.forEach((typeFilter) => {
setFilteredStores((prevStore) => {
return prevStore.filter((prevStore) => prevStore[typeFilter.property] !== typeFilter.name);
});
});
}
if (Object.keys(priceFilter).length > 0) {
setFilteredStores((prevStore) => prevStore.filter((store) => store[priceFilter.property] === priceFilter.name));
}
}, [jejuStores, typeFilters, priceFilter]);
return(
...
)
}
결과
아쉬운 점