본문 바로가기
웹/React

[React] useState를 이용해 리스트에 값 추가하기

by ohojee 2023. 9. 18.

내 옵션 리스트는 위와 같이 생겼다. 나는 여기서 선택한 카테고리들을 다 category list에 추가하고 싶었다. 하지만 아래와 같은 코드를 작성했을 때는 계속 마지막으로 선택한 카테고리 하나만 리스트에 들어갔다. 

var categoryList = []

const handleCategoryChange = (categories) => {
    categoryList.push(categories)
    setCategories(categories);
};

렌더링 될 때마다 값이 초기화되서 그런 것 같아서 useState를 써준 후

const [categoryList, setCategoryList] = useState([]); 

const updatedCategoryList = [...categoryList, selectedCategory];

전에 있던 카테고리 리스트와 이번에 선택된 카테고리를 추가하도록 작성했다. 하지만 이렇게 하면

처음 인문학을 선택하면 [인문학]이렇게 저장되는데, 다음에 과학을 선택하면 [인문학, 인문학, 과학] 이렇게 저장된다.

그래서 if문을 넣어주었다.

const handleCategoryChange = (selectedCategorie) => {
    // check if categories are duplicated, add them to the list if they are not duplicated
    if (!categoryList.includes(selectedCategorie)) {
        const updatedCategoryList = [...categoryList, selectedCategorie];
        setCategoryList(updatedCategoryList);
    }
    setCategories(selectedCategorie);
};

그랬더니 하나씩 잘 저장되는 것을 확인하였다.

댓글