Problem:
App.js
import { Text, View, Button, FlatList } from 'react-native';
import { useEffect, useState } from 'react';
import * as React from 'react';
const API = 'https://randomuser.me/api/users/';
const User = (props) => (
<View>
<Text>Name: {props.fname} {props.lname}</Text>
<Text>Country: {props.country}</Text>
</View>
);
const renderUser = ({item}) => <User fname={item.results[0].name.first} lname={item.results[0].name.last} country={item.results[0].location.country}/>;
export default function App() {
const [users, setUsers] = useState({});
useEffect(() => {
fetch(API)
.then((response) => response.json())
.then((json) => {setUsers(json);});}, []);
return (
<View>
<Text>{}</Text>
<Button title="add a user" onPress={() => {
fetch(API)
.then((response) => response.json())
.then((json) => {setUsers(json);}), []}}
/>
<FlatList data={users} renderItem={renderUser}/>
</View>
);
}
when I create a User, how should I reference the first and last name as well as the country from json? After looking online I thought this (item.results[0].name.first) was the way I was supposed to reference it but it still doesn’t work. What am I doing wrong
Solution:
Looks like you have set the wrong API. I just test:
https://randomuser.me/api/ returns correct results.
https://randomuser.me/api/users/ return 404 not found
.
UPDATE:
The response of API is:
{
"results": [
{
"gender": "male",
"name": {
"title": "Mr",
"first": "Harley",
"last": "Green"
},
"location": {
"street": {
"number": 5662,
"name": "Hoon Hay Road"
},
}
}
]
}
So you need to edit your code:
...
const renderUser = ({ item }) => {
return (
<>
<User
fname={item.name.first}
lname={item.name.last}
country={item.location.country}
/>
</>
);
};
export default function App() {
return (
<>
<View>
<Button
title="add a user"
onPress={() => {
fetch(API)
.then((response) => response.json())
.then((json) => {
setUsers(json);
}),
[];
}}
/>
<FlatList data={users.results} renderItem={renderUser} />
</View>
</>
);
}