Skip to content

Instantly share code, notes, and snippets.

@kwoncharles
Created March 1, 2020 09:18
Show Gist options
  • Save kwoncharles/1921be3bd70eb2dc4ba6c6d29f5a84d5 to your computer and use it in GitHub Desktop.
Save kwoncharles/1921be3bd70eb2dc4ba6c6d29f5a84d5 to your computer and use it in GitHub Desktop.
import { useState, useCallback } from 'react';
type returnType = [CheckItem[], (label: string) => void, () => void];
function useCheckList(checkList: CheckItem[]): returnType {
const [list, setList] = useState(checkList);
const onCheckItem = useCallback((label: string) => {
setList(prevList => prevList.map(item => {
if (label === item.label) {
return {
...item,
checked: !item.checked,
};
}
return item;
}));
}, []);
const checkAllItems = useCallback(() => {
/**
* 전체 체크하기를 눌렀을 때의 동작
* 1. 체크되지 않은 아이템이 있을 경우 전체 체크 활성화
* 2. 모두 체크돼있을 경우 전체 체크 해제
*/
setList(prevList => {
const targetStatus: boolean = !prevList.reduce(
(prev, cur) => prev && cur.checked,
true,
);
return prevList.map(item => ({
...item,
checked: targetStatus,
}));
});
}, []);
return [list, onCheckItem, checkAllItems];
}
export default useCheckList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment