Home > Net >  Values in <select><option> disappears after first selection
Values in <select><option> disappears after first selection

Time:09-17

I have a dropdown-menu made of select-tag and multiple option-tags The values of the -tags are pulled from an external api and mapped with .map into the tags. When I select an option, it gets the correct data but the dropdown is empty after that. I'd like to still have all the options in the dropdown after the first selection.

This is the code:

import React, {useState, createContext, useEffect} from "react";
import axios from "axios";
export const CountryContext = createContext();

export default function LocationContext(){

    const [countries, setCountries] = useState([]);

    const options = {
        method: 'GET',
        url: 'https://unogs-unogs-v1.p.rapidapi.com/aaapi.cgi',
        params: {t: 'lc', q: 'available'},
        headers: {
            'X-RapidAPI-Key': 'X',
            'X-RapidAPI-Host': 'unogs-unogs-v1.p.rapidapi.com'
        }
    };

    useEffect(() => {
        async function getData() {
            try {
                const response = await axios(options)
                setCountries(response.data.ITEMS)
                console.log(countries)
            } catch (e) {
                console.error(e);
            }
        }
        getData()
    },[])



    const selectCountry = (e) => {
        setCountries([e.target.value])
        console.log(countries);
    }
    
    return(
        <>
        <CountryContext.Provider value={countries}>
                <div className='country-selection-bar'>
                    <h2> SELECTEER
                    <select id='country'
                            className='country'
                            name='country'
                            onChange={selectCountry}
                    >
                        {
                           countries.map((country) => {
                                return (<option value={country[1]} key={country[0]}>{country[2]} </option>
                                );
                            })
                        }
                    </select>
                    </h2>
                </div>
            <Profile/>
        </CountryContext.Provider>
        </>
    )
}

CodePudding user response:

It looks like when you're selecting the country you're setting countries to e.target.value, so that would clear out whatever it previously was, which is the list of countries. You just need some other state to track the current selection. I picked out parts of your code as an example to try out.

const [selected, setSelected] = useState(null);

const selectCountry = (e) => {
    setSelected(e.target.value);
    console.log(countries);
}
  • Related