简体   繁体   中英

useState is not woking

can anyone tell me why this country not set in setCountry state via axios.i am fetching data from api via axios.i have below attched my response data from api.

function Country() {
    const [Country, setCountry] = useState([])

    useEffect(()=>{
        //IF [] , runs only once
        const fetchUrl="https://api.first.org/data/v1/countries"
       async function fetchData(){
           
           const request=await axios.get(fetchUrl);
           setCountry(request.data);
           return request;
 
       }
       fetchData();
    
    },[]);

    return (
        <div>
            <button >load country</button>
            <select>
            

            </select>
            
        </div>
    )
}

export default Country

response data from api in console.log

{status: "OK", status-code: 200, version: "1.0", total: 251, limit: 100, …}
access: "public"
data: {DZ: {…}, AO: {…}, BJ: {…}, BW: {…}, BF: {…}, …}
limit: 100
offset: 0
status: "OK"
status-code: 200
total: 251
version: "1.0"

The data you are accessing through API response is an object. Maybe what you can do is something like this -

setCountry(Object.values(request.data));

The request.data will be an object with below structure -

request.data = {
       "DZ":{"country":"Algeria","region":"Africa"},
       "AO":{"country":"Angola","region":"Africa"},
       "BJ":{country":"Benin","region":"Africa"}
       ....
}

Now passing this into Object.values will return an array which you can directly set into the component state.

Object.values(request.data) = [
   {country: "Algeria", region: "Africa"},
   {country: "Angola", region: "Africa"},
   {country: "Benin", region: "Africa"},
   ....
]

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