I am working on a D&D app with react native. When I try to render the code, the screen is empty and the console.log shows an array.
The code:
export default () => {
const [loading, setLoading] = useState(true)
const [monsters, setMonsters] = useState([])
console.log("🚀 ~ file: Monsters.js ~ line 10 ~ monsters", monsters)
const fetchMonsters = async () => {
const response = await fetch('https://www.dnd5eapi.co/api/monsters')
const data = await response.json()
setMonsters(data)
setLoading(false)
}
useEffect(() => {
fetchMonsters()
}, [])
return (
<View style={styles.container}>
{loading ? <Text>Cargando...</Text> :
<FlatList
style={styles.list}
data={monsters}
renderItem={({item}) => <Text>{item.name}</Text>}
/>}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'flex-start',
justifyContent: 'flex-start',
},
});
When I fetch the users API all the items render in the list, but when I fetch the monster API the screen shows nothing.
2
Answers
The issue is caused by the difference in structure of 2 APIs.
https://jsonplaceholder.typicode.com/users
It is an array with listing objects.
https://www.dnd5eapi.co/api/monsters
It is an Object with array named ‘results’.
So, your code in
fetchMonsters
should beThat’s happening because you are storing whole JSON response in your state instead of
results
array inside that just update yourfetchMonsters
function like this and that should do it