I have created new custom selectbox using React. There is pre-populated array which I am loading on component load (using useEffect). When user search for any non existing country there would be a option to add. So I used useState hooked. Code is as under :-
const [countries, setCountries] = useState([]);
Countries list :-
[
{"value": 1, "label": "Singapore"},
{"value": 2, "label": "Malaysia"},
{"value": 3, "label": "Indonesia"},
{"value": 4, "label": "Phillipines"},
{"value": 5, "label": "Thailand"},
{"value": 6, "label": "India"},
{"value": 7, "label": "Australia"},
{"value": 8, "label": "Pakistan"}
]
const handleHTTPRequest = () => {
service.getData()
.then(res => {
setCountries(res);
})
.catch((err) => console.error(err))
}
useEffect(() => {
handleHTTPRequest()
})
I am checking the searched country in the array and if not exists I simply add in array
const addCountry = (country) => {
let isRecordExist = countries.filter(c => c.label === country).length > 0 ? true : false;
const obj = {
value: countries.length + 1,
label: country
}
let updatedVal = [...countries, obj]
setSelectedCountry(country)
if (!isRecordExist) {
**setCountries**(updatedVal) // updating array
}
}
The problem is its not updating although I can see data in updatedVal.
Entire code is here :-