I'm trying to call external api during the first time when the component is rendered and get the list of all countries with async/await function. However I got empty state back after I called the setState function. I'm quite new to RN and been stuck in this problem for days now. Appreciated if anyone can help. Here's what I've been trying to do...
import React, { useState, useEffect } from "react";
import {
Platform,
Text,
View,
TextInput,
StyleSheet,
FlatList,
} from "react-native";
import { FontAwesome } from "react-native-vector-icons";
import countryapi from "../src/countryapi";
const CountryScreen = () => {
const [countryDetails, setCountryDetails] = useState([]);
// Fetch country details { country name, iso3, iso2, country flag }
const countrySearchAPI = async () => {
try {
const countriesData = await countryapi.get();
const countries = countriesData.data;
for (const country in countries) {
const { iso2 } = countries[country];
let countriesDetailsData = await countryapi.get(`/${iso2}`);
let { name, iso3, emoji } = countriesDetailsData.data;
setCountryDetails([
...countryDetails,
{
countryName: name,
iso3,
iso2,
countryFlag: emoji,
},
]);
console.log(countryDetails);
}
} catch (e) {
console.log(e);
}
console.log(countryDetails);
};
useEffect(() => {
countrySearchAPI();
}, []);
return (
<View>
<View style={styles.searchSection}>
<FontAwesome name="search" size={30} />
<TextInput placeholder="Search for Country" style={styles.inputBox} />
</View>
{/* <FlatList
data={countryDetails}
renderItem={({ item }) => {
return (
<Text>
{item.countryName}
{item.countryFlag}
</Text>
);
}}
keyExtractor={(item) => item.id.toString()}
/> */}
</View>
);
};