Description of bug
I'm trying to set a value returned by the API in react-select to edit a record, but I noticed the following:
When I use react-select without Unform I can set the value property and it works correctly.
Below is a link to an example that highlights the error:
https://codesandbox.io/s/react-select-not-showing-value-gyhzy?file=/src/components/Select.js
Steps to reproduce the behavior:
Obs.: If you click on select to choose an option, the selected value will render.
@taikio Try this
useEffect(() => {
registerField({
name: fieldName,
ref: selectRef.current,
getValue: (ref: any) => {
if (rest.isMulti) {
if (!ref?.state?.value) {
return [];
}
return ref.state.value.map((option: OptionTypeBase) => option.value);
} else {
if (!ref?.state?.value) {
return "";
}
if (Array.isArray(ref?.state?.value)) {
return ref?.state?.value[0]?.value;
}
return ref?.state?.value?.value;
}
},
setValue: (ref: any, value: any) => {
if (rest.isMulti && Array.isArray(value)) {
const items = ref?.props?.options?.filter((option: any) =>
value.includes(option.value)
);
ref?.select.setValue(items);
} else {
const item = ref?.props?.options?.filter(
(option: any) => option.value === value
);
if (item && item.length > 0) {
ref?.select?.setValue(item);
}
}
},
});
}, [fieldName, registerField, rest.isMulti]);
@dougg0k it works perfectly, thanks for the help
You're welcome. I've updated the snippet to support multi values.
Most helpful comment
@taikio Try this