I have 2 select elements (I want to have 3 - country, region and city). If user check country, region select must display only regions from selected country. I wrote this code but after I select country I have the error:
props.countries.map is not a function
My code
const TextMessage = (props) => {
const [countries, setCountries] = useState([]);
const [regions, setRegions] = useState([]);
const [rowRegions, setRowRegions] = useState([]);
const [cities, setCities] = useState([]);
const [checkCountry] = useState(1);
useEffect(() => {
axios.get(`/ajax/countries`)
.then(res => {
setCountries(res.data)
})
axios.get(`/ajax/regions`)
.then(res => {
setRegions(res.data)
})
axios.get(`/ajax/cities`)
.then(res => {
setCities(res.data)
})
}, []);
const handleCountryCheck = (country) => {
setCheckCountry(1);
console.log(country + ' ' + checkCountry);
}
return(
<div>
<Countries countries={countries}
handleCountryCheck = {handleCountryCheck}/>
<Regions regions={regions}
checkCountry = {checkCountry}
/>
</div>
);
}
const Countries = (props) => {
const handleCountryCheck = (e) => {
props.handleCountryCheck(e.target.value);
}
const list = props.countries.map(item => <option key={item.id} value={item.id}>{item.name}</option>);
useEffect(() => {
})
return(
<select onChange={handleCountryCheck}>
{list}
</select>
);
}
const Regions = ({ regions, checkCountry }) => {
const list = [];
regions.forEach((item) => {
if(checkCountry === item.country_id){
list.push(<option key={item.id}>{item.name}</option>);
}
});
return(
<select>
{list}
</select>
);
}
export default TextMessage;
How I can solve my problem without redux? I know that I can do that but (if it's possible) I want to do without redux. Any idea?
@Edit
I make a mistake with handleCountryCheck function but I changed it. But this is not solve my problem. Look at this example
const handleCountryCheck = (country) => {
setCheckCountry(1);
}
This code works correctly. Any times display region from first country. Lets change it
const handleCountryCheck = (country) => {
setCheckCountry(country);
console.log(country + '' checkCountry);
}
Any time I select country, I have a empty region's select. Other problem: checkCountry hook display always old value. For example - I checked UK but it display me US becouse this country was checked before.