From 7219c17d30b1ddffdec57260fec007152e1db850 Mon Sep 17 00:00:00 2001 From: Keith Grant Date: Thu, 9 Jan 2020 15:01:44 -0800 Subject: [PATCH] start usePFSelect hook --- .../screens/Template/shared/LabelSelect.jsx | 45 +++++++++++-------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/awx/ui_next/src/screens/Template/shared/LabelSelect.jsx b/awx/ui_next/src/screens/Template/shared/LabelSelect.jsx index 33830fe8bb..c9072e2950 100644 --- a/awx/ui_next/src/screens/Template/shared/LabelSelect.jsx +++ b/awx/ui_next/src/screens/Template/shared/LabelSelect.jsx @@ -12,6 +12,31 @@ function setToString(labels) { return labels; } +// TODO: extract to shared file +function usePFSelect(value, options, onChange) { + const [currentValue, setCurrentValue] = useState([]); + + useEffect(() => { + if (value !== currentValue && options.length) { + const syncedValue = value.map(item => + options.find(i => i.id === item.id) + ); + setCurrentValue(syncedValue); + } + /* eslint-disable-next-line react-hooks/exhaustive-deps */ + }, [value, options]); + + const handleSelect = (event, item) => { + if (currentValue.includes(item)) { + onChange(currentValue.filter(i => i.id !== item.id)); + } else { + onChange(currentValue.concat(item)); + } + }; + + return [currentValue, handleSelect]; +} + async function loadLabelOptions(setLabels, onError) { let labels; try { @@ -39,35 +64,17 @@ async function loadLabelOptions(setLabels, onError) { function LabelSelect({ value, placeholder, onChange, onError }) { const [options, setOptions] = useState([]); - const [currentValue, setCurrentValue] = useState([]); + const [currentValue, handleSelect] = usePFSelect(value, options, onChange); const [isExpanded, setIsExpanded] = useState(false); const toggleExpanded = () => { setIsExpanded(!isExpanded); }; - const handleSelect = (event, item) => { - if (currentValue.includes(item)) { - onChange(currentValue.filter(i => i.id !== item.id)); - } else { - onChange(currentValue.concat(item)); - } - }; - useEffect(() => { loadLabelOptions(setOptions, onError); }, [onError]); - useEffect(() => { - if (value !== currentValue && options.length) { - const syncedValue = value.map(item => - options.find(i => i.id === item.id) - ); - setCurrentValue(syncedValue); - } - /* eslint-disable-next-line react-hooks/exhaustive-deps */ - }, [value, options]); - const renderOptions = opts => { return opts.map(option => (