Created
July 9, 2020 12:47
-
-
Save g4rcez/903023fe71c59e24134df221915cebf6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from "react"; | |
type Checks = Map<string, boolean>; | |
const createFromMap = (list: Input[]): Checks => new Map(list.map((x) => [x.name!, x.checked!])); | |
const getOnlyChecked = (map: Checks) => { | |
const values: string[] = []; | |
map.forEach((checked, key) => (checked ? values.push(key) : undefined)); | |
return values; | |
}; | |
export const useCheckbox = (list: Input[]) => { | |
const [map, setMap] = useState(() => createFromMap(list)); | |
const [values, setValues] = useState<string[]>([]); | |
useEffect(() => setMap(createFromMap(list)), [list]); | |
useEffect(() => setValues(getOnlyChecked(map)), [map]); | |
const onChange: Input["onChange"] = (e) => { | |
const { name, checked } = e.target; | |
map.set(name, checked); | |
setMap(new Map(map)); | |
}; | |
const get = (item: string) => { | |
const findItem = list.find((x) => x.name === item); | |
if (findItem) { | |
return { | |
...findItem, | |
onChange, | |
value: findItem.name, | |
children: undefined, | |
checked: !!map.get(item), | |
}; | |
} | |
}; | |
return { map, values, onChange, get }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment