Reputation: 13
I'm just training how to consume apis in react-native with useEffects and in console.log () returns the results, but in the view it doesn't show, I think it's the keyExtractor or not ...
const api = 'https://randomuser.me/api/?&results=2';
const Detalhes = () => {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
setIsLoading(true);
fetch(api)
.then((response) => response.json())
.then((results) => {
setData(results);
setIsLoading(false);
console.log(results);
})
.catch((err) => {
setIsLoading(false);
setError(err);
});
}, []);
if (isLoading) {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator size="large" color="#5500dc" />
</View>
);
}
if (error) {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text style={{fontSize: 18}}>
Error...
</Text>
</View>
);
}
and this is the code with FlatList that should be returned in View and as said, I can see the result in console.log (react native debug)
<SafeAreaView>
<FlatList
data={data}
keyExtractor={item => item.first}
renderItem={({item}) => (
<View style={styles.metaInfo}>
<Text style={styles.text}>
{`${item.name.first} ${item.name.last}`}
</Text>
</View>
)}
/>
</SafeAreaView>
Upvotes: 1
Views: 75
Reputation: 519
Try to see again console.log(results)
. Api response is an object { results, info }
, not an array. The results property of results is array.
Replace setData(results);
by setData(results.results);
to resolve your problem.
Sorry for my bad English.
Upvotes: 2
Reputation: 6967
You are giving name
in your keyExtractor
which could be same repeat so It won't work. Try changing keyExtractor
like below to provide unique index for each item
keyExtractor={(item,index)=>index.toString()}
Upvotes: 1