Home > Mobile >  Fetch api not displaying my output in react native
Fetch api not displaying my output in react native

Time:09-23

am stuck with a problem while getting user data and display as an output, am using fake API. don't know where am wrong please try to fix my problem. if you have any queries please free feel to ask any time.

import React, { useEffect, useState } from 'react';
import { Text, View, FlatList } from 'react-native';
// import { Card, Title, Paragraph } from 'react-native-paper';
import { Searchbar } from 'react-native-paper';

export default function Home() {
  const [searchquery, setSearchquery] = React.useState();
  const [data, setData] = useState([]);

  const getMovies = async () => {
    try {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/users'
      );
      const json = await response.json();
      setData(json.users);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    getMovies();
  }, []);

  return (
    <View>
      <Searchbar
        placeholder="Search Books"
        onChangeText={(query) => setSearchquery(query)}
        value={searchquery}
        style={{ marginTop: 30, marginHorizontal: 10 }}
      />
      <FlatList
        data={data}
        keyExtractor={({ id }, index) => id}
        renderItem={({ item }) => <Text>{item.city}</Text>}
      />
    </View>
  );
}

CodePudding user response:

Insted of setData(json.users); try setData(json) and renderItem={({ item }) => <Text>{item.city}</Text>} try renderItem={({ item }) => <Text>{item.address.city}</Text>}

CodePudding user response:

Try to handle the response like this:

const response = await fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(res => console.log(res)) //maybe need to JSON.Stringify() it
.catch(err => console.log("Error: "   err))

You should get a response this way and you can store it in the second then block.

CodePudding user response:

Insted of {item.city} Try {item.address["city"]}

  • Related