简体   繁体   中英

Select value from dropdown menu and setting setCountries() to the selected value - React JS

This actually seems rather simple and it seems like I am close to getting it right but it is not working properly - still learning: :))

This is some context regarding this quest and it seems to work there.

I am getting data from the Countries REST API and I am setting the state by using const [countries, setCountries] = useState([]);

Now Ive got a dropdown menu where I want to display the countries using the selected value which is a region from the list of regions.

<form>
    <select
        name="regions"
        id="inputRegion"
        onChange={filterByRegion}
    >
        <option value="Africa">Africa</option>
        <option value="Americas">Americas</option>
        <option value="Asia">Asia</option>
        <option value="Oceania">Oceania</option>
        <option value="Polar">Polar</option>
    </select>
</form>
const filterByRegion = (e) => {
        handleSubmit(e.target.value);
        e.preventDefault();
    };

    function handleSubmit(value) {
        const filteredByRegionCountries = countries.filter(
            (country) => country.region === value
        );
        setCountries(filteredByRegionCountries);

On the region button itself I am calling onChange={filterByRegion}

After one selects one region it displays the data properly but after you try to use another region it displays no countries at all. I am thinking it has something to do with setCountries(filteredbyRegionsCountries)?

Why is setCountries not being updated properly even though we are saying that it should be updated with whatever regions is selected by using the handleSubmit() function?

Does anybody have any insight? Merci and thank you in advance!

By using

countries.filter((country) => country.region === value);

you filter out all countries that don't have the name of the selected country. See the https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter reference.

When you first select "Europe", for instance, you filter out everything that isn't Europe and when you select another country, let's say you select "Polar", you filter out "Europe" as well, because it filters out everything that isn't "Polar".

You could try logging out the countries array to the console after each change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM