I am trying to use flatlist with api call in react-native but I get an error "tried to get frame or out of range index NaN". The response of api is array.
My flatlist is like below
<FlatList
data={dataSource}
renderItem={({ item}) => {
return (
<Text style={{ fontSize: 16, color: "black" }}>
{item.name}
</Text>);
}}
/>
My api call is like below
const [dataSource, setDataSource] = useState([]);
useEffect(() => {
const getData = () => {
try {
const response = await axios.get(
"https://restcountries.eu/rest/v2/name/united"
);
console.log(Array.isArray(response.data)); //true
setDataSource({ dataSource: response.data });
setLoading(false);
} catch (err) {
console.log(err);
}
};
getData();
}, []);
What can I do to fix this issue ?
The useState
hook works differently from a class-based this.setState()
.
Refer to the official documents for more information
https://reactjs.org/docs/hooks-state.html#updating-state
The correct syntax in your case would be
try {
const response = await fetchData();
setDataSource(response.data); // Array
setLoading(false);
} catch (err) {
console.log(err);
}