skip to Main Content

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


  1. The issue is caused by the difference in structure of 2 APIs.

    https://jsonplaceholder.typicode.com/users

    It is an array with listing objects.

    [
      {
        "id": 1,
        "name": "Leanne Graham",
        ...
      },
    ]
    

    https://www.dnd5eapi.co/api/monsters

    It is an Object with array named ‘results’.

    {
      "count":334,
      "results:[
          {
             "index":"aboleth",
             "name":"Aboleth",
                 ...
          },
      ]
    }
    

    So, your code in fetchMonsters should be

    setMonsters(data.results);
    
    Login or Signup to reply.
  2. That’s happening because you are storing whole JSON response in your state instead of results array inside that just update your fetchMonsters function like this and that should do it

         const fetchMonsters = async () => {
              const response = await fetch('https://www.dnd5eapi.co/api/monsters')
              const data = await response.json()
              setMonsters(data?.results)
              setLoading(false)
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search