FlatList receiving undefined values after fetching json - json

I need to render a FlatList after fetching a json containing connections. The following piece of code runs correctly but the travel object inside the renderItem is always undefined.
import {Text, View, FlatList, ActivityIndicator} from 'react-native';
import React, {useEffect, useState} from 'react';
/**
* http://transport.opendata.ch/v1/connections?from=8575201&to=8503000
*/
export function TravelsScreen({navigation}) {
const [isLoading, setLoading] = useState(true);
const [travels, setTravels] = useState([]);
useEffect(() => {
fetch('http://transport.opendata.ch/v1/connections?from=8575201&to=8503000')
.then(response => response.json())
.then(json => setTravels(json.connections))
.catch(error => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<View style={{flex: 1, padding: 24}}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={travels}
renderItem={({travel}) => <Text>Travel: {console.log(travel)}</Text>}
keyExtractor={travel => travel.from.departureTimestamp.toString()}
/>
)}
</View>
);
}

Please update your FlatList to :
<FlatList
data={travels}
renderItem={({item}) => {console.log(item)}}
//other properties
/>
From official documentation the renderItem method takes out item from the FlatList array and since you are using the destructuring syntax to extract it, you should explicitly use item. An alternative without the destructuring syntax would look like :
<FlatList
data={travels}
renderItem={(travel) =>{ console.log(travel.item)}}
//other properties
/>

Related

I can't display the data from an API into a FlatList, but I see it in my console.log. What is the problem?

Console logging my react native app shows the data I fetch from an API. The problem now is that it is not displaying in the FlatList.
const HealthLinkMain = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(API_URL, {
method: "GET",
headers: {
Authorization: `Bearer ${TOKEN}`,
},
});
setData(response.data)
} catch (error) {
console.error(error);
}
};
fetchData();
}, []);
return (
<View style={styles.container}>
<Text>Test</Text>
<FlatList
data={data.data}
renderItem={(item) => (
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)}
keyExtractor={(item, index) => item.clinic_name}
/>
</View>
);
};
I think the problem might be in your renderItem as you haven't destructured the item, try this:
renderItem = {({ item }) => {
return (
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)
}}
You can also seperate it the renderItem into a function of it's own which a lot of people tend to do:
const renderItem = ({item}) => {
return(
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)
}
and then change the flatlist calling function accordingly:
<FlatList
data={data.data}
renderItem={renderItem}
keyExtractor={(item, index) => item.clinic_name}
/>

How to Fetch Data from Firebase Realtime Database in React Native App

How can I fetch data from Firebase Realtime Database using the below method?
My Realtime Database:
import React, { useEffect, useState, useContext, } from 'react';
import { View, Text, Image, StyleSheet, ScrollView, SafeAreaView, ActivityIndicator, FlatList, } from 'react-native';
import {firebase} from '../config';
export default function App() {
const [users, setUsers] = useState([]);
const todoRef = firebase.firestore().collection('testing');
useEffect(() => {
todoRef.onSnapshot(
querySnapshot => {
const users = []
querySnapshot.forEach((doc) => {
const { one, two, three, four
} = doc.data()
users.push({
id: doc.id,
one, two, three, four
})
})
setUsers(users)
}
)
}, [])
return (
<View style={{ backgroundColor: theme.viewOne, }}>
{isLoading ? <ActivityIndicator /> : (
<FlatList
ListHeaderComponent={
<Image source={require('./AllImage/qq2.jpg')}
style={{ width: "auto", height: 150, resizeMode: "cover", }} />
}
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<View style={styles.container}>
<View style={styles.item}>
<Text style={styles.mainText}>{item.one}</Text>
</View>
<View style={styles.item}>
<Text style={styles.mainText}>{item.two}</Text>
</View>
</View>
)}
/>
)}
</View>
);
};
Rahul for react-native you can implement it like this instead of using async-await.
You need to connect your app to database like this -
import { firebase } from '#react-native-firebase/database';
const reference = firebase
.app()
.database('https://<databaseName>.<region>.firebasedatabase.app/')
.ref('/users/123');
Then you can perform read-write transactions like this -
import database from '#react-native-firebase/database';
database()
.ref('/users/123')
.once('value')
.then(snapshot => {
console.log('User data: ', snapshot.val());
});
The article has a detailed implementation and you can choose to persist data easily as well. Hope it helps!

Handling JSON response React Native

I'm following the React Native documentation for fetching JSON from an API (https://reactnative.dev/docs/network). I'm new to react and wanting to fetch a wordpress list of posts through its API, but the example they use is very simple and structured differently to how the object is returned from WP.
The problem I'm having is that it is returning the JSON, but I'm unsure how to reference each item I want to display in my flatlist. The line of problem is;
.then((json) => setData(json.movies))
For this WP returned JSON, there is no movies (obviously), in the absence of a referable point what would I specify instead?
My code;
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
export default App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://public-api.wordpress.com/wp/v2/sites/derbyfutsal.com/posts')
.then((response) => response.json())
.then((json) => setData(json.movies))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Text>{item.title}, {item.excerpt}</Text>
)}
/>
)}
</View>
);
};
You dont have to specify anything, you can directly set the response to the state value and use it in the flatlist.
I've updated the code to display the id instead of title as its an object. You can change it anyway you want and use it.
const App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://public-api.wordpress.com/wp/v2/sites/derbyfutsal.com/posts')
.then((response) => response.json())
.then((json) => {
setData(json)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Text>{item.id}</Text>
)}
/>
)}
</View>
);
};

React Native flatlist specific data

Im requiring data from a local json file just for test purposes (On a ideal world im going to fetch data from a remote url) this json file is an array with 8 objects, but I need the flatlist just to render the first 3, how can I do that?
My code:
import extratoData from "./extratoData.json"
export default function Body () {
const [data, setData] = useState([])
useEffect(() => {setData(extratoData)}, [])
return(
<FlatList
data={extratoData}
renderItem={({item}) => <ExtratoRenderItem title={item.title} amount={item.amount} date={item.date} time={item.time} cashback={item.cashBack}/>}
keyExtractor={(item, index) => index.toString()}
/>
)
You can just use the Array.prototype.slice() method.
var firstThree = extratoData.slice(0, 3);

How can i solve uniqe key prop problem in React native

I have React Native project and when i try to build my phone, i'm getting this error message. Warning: Each child in an array or iterator should have a unique "key" prop. But it works on computer emulator.
Here is json data: http://hazir.net/api/match/today
and here is my codes,
import React from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class Matches extends React.Component {
constructor(props){
super(props);
this.state ={ isLoading: true}
}
componentDidMount(){
return fetch('http://hazir.net/api/match/today')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render(){
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.matchId}, {item.matchDate}</Text>}
keyExtractor={({id}, index) => id}
/>
</View>
);
}
}
The easiest solution would be to update your keyExtractor as it appears to not be working. It doesn't look like your data has an id property, however it does have a matchId property. This means you could do something like the following.
<FlatList
...
keyExtractor={({matchId}, index) => matchId.toString()}
/>
Alternatively you could use the index as the key and do this
<FlatList
...
keyExtractor={({matchId}, index) => index.toString()}
/>