const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { value } = e.target;
const valueLength = Hangul.disassemble(value).length;
const searchValueLength = Hangul.disassemble(searchValue).length;
// 입력값을 추가할때
if (valueLength > searchValueLength) {
dispatch(filterProducts(value));
} else if (valueLength < searchValueLength) {
dispatch(rollbackProducts(value));
}
dispatch(filterBrands(value));
setSearchValue(value);
};
const initialState = {
mockdata: [] as searchInfo[],
brandList: [] as string[],
filterList: {
products: [] as searchInfo[],
brands: [] as string[],
},
};
여기서 searchInfo타입으로 type assertion을 주었다.
searchInfo 인터페이스를 살펴보면,
그냥 : searchInfo[]로 하면 안되나?
const filterProduct = ({
targetList,
searchValue,
}: {
targetList: searchInfo[];
searchValue: string;
}) =>
targetList.filter((item) => {
const modifiedMockData = item.제품명.replaceAll(' ', '').toLowerCase();
const modifiedSearchValue = searchValue.replaceAll(' ', '').toLowerCase();
if (Hangul.search(modifiedMockData, modifiedSearchValue) < 0) {
return false;
} else {
return true;
}
});
이 filterProduct함수를 사용해 리듀서를 작성했다.
filterProducts(state, action: PayloadAction<string>) {
const isEmptyValue = action.payload.trim();
if (!isEmptyValue) {
state.filterList.products = [];
} else {
const isProduct =
state.filterList.products.length === 0
? state.mockdata
: state.filterList.products;
state.filterList.products = filterProduct({
targetList: isProduct,
searchValue: action.payload,
});
}
},
rollbackProducts(state, action: PayloadAction<string>) {
const isEmptyValue = action.payload.trim();
if (!isEmptyValue) {
state.filterList.products = [];
} else {
state.filterList.products = filterProduct({
targetList: state.mockdata,
searchValue: action.payload,
});
}
},
filterBrands(state, action: PayloadAction<string>) {
const isEmptyValue = action.payload.trim();
if (!isEmptyValue) {
state.filterList.brands = [];
} else {
state.filterList.brands = findBrandinBrands({
brandList: state.brandList,
searchValue: action.payload,
});
}
},
fetchMockData(state, action: PayloadAction<searchInfo[]>) {
state.mockdata = action.payload;
},
getBrandsList(state) {
state.brandList = getBrandsInData(state.mockdata);
},