'react-select defaultValue's value has changed but not updating what is shown in the UI
I have 2 react-select, one is for methodGroups, the other is methods.
methodGroups: [{value: 1, label: 'Group-1'}, {value: 2, label: 'Group-2'}, ...]
methods: [{value: 1, label: 'method-1', isActive: 1}, {value: 2, label: 'method-2', isActive: 0}, ...]
When I select from methodGroups, the methods select should automatically set all the isActive = 1 as selected.
What I did was,
methodGroups Select:
const handleGroupChange = () => {
// fetch from api
let { activeMethods, inactiveMethods } = apiData;
let temp1 = activeMethods.map(obj => ({value: obj.id, label: obj.method, isActive: 1}));
let temp2 = inactiveMethods.map(obj => ({value: obj.id, label: obj.method, isActive: 0}));
setMethods(temp1.concat(temp2));
}
<CustomSelect
options={methodGroups}
onChange={handleGroupChange}
/>
methods Select:
const handleMethodsChange = (values) => {
setMethods(values);
}
<CustomSelect
defaultValue={methods.filter(obj => obj.isActive == 1)}
options={methods}
isMulti
onChange={handleMethodsChange}
/>
At first, when I select from methodGroups it shows the defaultValues on methods select.
But when I select new from methodGroups, the props of methods select has changed, but the default value that was being displayed in the UI is still the defaultValue of the previous selected methodGroups
BTW, I made the Select as a separate component, like this:
CustomSelect.js
import React from 'react';
import { useEffect } from 'react';
import { useState } from 'react';
import Select from 'react-select';
function CustomSelect({
defaultValue,
options,
isMulti,
onChange
}) {
// const [defVal, setDefVal] = useState(defaultValue);
// useEffect(() => {
// console.log('defaultValue ', defaultValue);
// setDefVal(defaultValue);
// }, [defaultValue]);
return (
<Select
defaultValue={defaultValue}
options={options}
isMulti={isMulti}
onChange={onChange}
/>
)
}
export default CustomSelect
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
