|
| 1 | +import {produce} from 'immer'; |
| 2 | +import PropTypes from 'prop-types'; |
| 3 | +import React, {useEffect} from 'react'; |
| 4 | + |
| 5 | +import ReactSelect from 'components/admin/forms/ReactSelect'; |
| 6 | + |
| 7 | +const CatalogSelect = ({ |
| 8 | + name, |
| 9 | + htmlId, |
| 10 | + availableCatalogsState, |
| 11 | + catalogDomein, |
| 12 | + catalogRsin, |
| 13 | + onChange, |
| 14 | + isClearable = true, |
| 15 | +}) => { |
| 16 | + const {loading, availableCatalogs, error} = availableCatalogsState; |
| 17 | + |
| 18 | + const onCatalogChange = event => { |
| 19 | + const {value} = event.target; |
| 20 | + const splitValue = value.split('-'); |
| 21 | + onChange( |
| 22 | + produce(formData, draft => { |
| 23 | + draft.catalogDomein = splitValue[0]; |
| 24 | + draft.catalogRsin = splitValue[1]; |
| 25 | + }) |
| 26 | + ); |
| 27 | + }; |
| 28 | + |
| 29 | + const options = |
| 30 | + loading || error |
| 31 | + ? [] |
| 32 | + : availableCatalogs.map(({domein, rsin}) => { |
| 33 | + return {value: `${domein}-${rsin}`, label: `${domein} (RSIN: ${rsin})`}; |
| 34 | + }); |
| 35 | + |
| 36 | + // ensure that if no valid value is present, the first possible option is set ( |
| 37 | + // synchronize the UI state back to the form state) |
| 38 | + useEffect(() => { |
| 39 | + // do nothing if no options have been loaded |
| 40 | + if (loading || !availableCatalogs.length) return; |
| 41 | + |
| 42 | + // check if a valid option is selected, if this is the case -> do nothing |
| 43 | + const isOptionPresent = availableCatalogs.find( |
| 44 | + catalog => catalog.domein === catalogDomein && catalog.rsin === catalogRsin |
| 45 | + ); |
| 46 | + if (isOptionPresent) return; |
| 47 | + |
| 48 | + // otherwise select the first possible option and persist that back into the state |
| 49 | + onChange( |
| 50 | + produce(formData, draft => { |
| 51 | + draft.catalogDomein = availableCatalogs[0].domein; |
| 52 | + draft.catalogRsin = availableCatalogs[0].rsin; |
| 53 | + }) |
| 54 | + ); |
| 55 | + }, []); |
| 56 | + |
| 57 | + return ( |
| 58 | + <ReactSelect |
| 59 | + name={name} |
| 60 | + value={`${catalogDomein}-${catalogRsin}`} |
| 61 | + options={options} |
| 62 | + htmlId={htmlId} |
| 63 | + onChange={onCatalogChange} |
| 64 | + emptyValue="" |
| 65 | + isClearable={isClearable} |
| 66 | + /> |
| 67 | + ); |
| 68 | +}; |
| 69 | + |
| 70 | +CatalogSelect.propTypes = { |
| 71 | + name: PropTypes.string.isRequired, |
| 72 | + availableCatalogsState: PropTypes.object.isRequired, |
| 73 | + catalogDomein: PropTypes.string.isRequired, |
| 74 | + catalogRsin: PropTypes.string.isRequired, |
| 75 | + onChange: PropTypes.func.isRequired, |
| 76 | + isClearable: PropTypes.bool, |
| 77 | +}; |
| 78 | + |
| 79 | +export default CatalogSelect; |
0 commit comments