test-crud
Version:
es una prueba acerca de como publicar un package name
145 lines (126 loc) • 3.37 kB
JSX
import React, { useState, useEffect } from 'react'
import { useFormikContext } from 'formik'
import MultiSearchInput from '../inputs/searchInput/MultiSearchInput'
function AppMultiSearchInput({
name,
label,
valueProperty = 'id',
labelProperty,
asyncData,
asyncParameters,
onSelect,
endAdornment = null,
defaultValues = null,
...rest
}) {
const [open, setOpen] = useState(false)
const [options, setOptions] = useState([])
const loading = open && options.length === 0
const {
setFieldValue,
setFieldTouched,
errors,
touched,
values,
initialValues,
} = useFormikContext()
useEffect(() => {
let active = true
if (!loading) return undefined
if (asyncData) {
asyncData(asyncParameters).then((res) => {
if (res.data) {
if (active) setOptions(res.data)
}
})
}
return () => {
active = false
}
}, [loading])
useEffect(() => {
if (!open) {
setOptions([])
}
}, [open])
useEffect(() => {
if (values?.[name] && Array.isArray(values[name])) {
if (asyncData) {
asyncData(asyncParameters).then((res) => {
if (res.data) {
const selectedItems = getSelectedItems(res.data)
setFieldValue(name, selectedItems)
onSelect && onSelect([...selectedItems])
}
})
} else {
if (rest.options && rest.options.length > 0) {
const selectedItems = getSelectedItems(rest.options)
setFieldValue(name, selectedItems)
}
}
}
}, [initialValues])
useEffect(() => {
if (asyncData) {
asyncData(asyncParameters).then((res) => {
if (res.data) {
setOptions(res.data)
const selectedItems = getSelectedItems(res.data)
setFieldValue(name, selectedItems)
onSelect && onSelect([...selectedItems])
}
})
}
}, [asyncParameters])
useEffect(() => {
if (rest.options && rest.options.length > 0) {
setOptions(rest.options)
}
}, [rest.options])
const getSelectedItems = (listItems) => {
const selectedItems = []
listItems.map((listItem) => {
if (
values?.[name]?.find(
(propertyItem) =>
propertyItem?.[valueProperty] === listItem[valueProperty] ||
propertyItem?.[valueProperty] === listItem['id']
)
)
selectedItems.push(listItem)
})
return selectedItems
}
const handleSelect = (items) => {
if (!items) return
setFieldValue(name, [...items])
onSelect && onSelect([...items])
}
return (
<div>
<MultiSearchInput
multiple={true}
name={name}
label={label}
value={values?.[name] || []}
options={options}
getOptionLabel={(option) => option?.[labelProperty]}
isOptionEqualToValue={(option, value) =>
option?.[valueProperty] === value
}
open={open}
onOpen={() => setOpen(true)}
onClose={() => setOpen(false)}
loading={loading}
onBlur={() => setFieldTouched(name)}
onChange={(event, newValue) => handleSelect(newValue)}
touched={touched[name]}
errorMessage={errors[name]}
endAdornment={endAdornment}
{...rest}
/>
</div>
)
}
export default AppMultiSearchInput