I have a React Native application and I want to:
Here's my source code
import React, { useEffect, useState } from 'react';
import { SafeAreaView, FlatList, Text, View } from 'react-native';
import {parseString} from 'xml2js'
export default function App() {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
console.log(data);
useEffect(() => {
var url = "http://www.xmltv.co.uk/feed/9437"
fetch(url)
.then((response) => response.text())
.then((responseText) => {
parseString(responseText, function (err, result) {
console.log(result);
// Where do I set data? setData(responseText);
return result;
});
this.setState({
datasource : result
})
})
.catch((error) => {
console.log('Error fetching the feed: ', error);
})
.finally(() => setLoading(false));
});
return (
<SafeAreaView style={{ flex: 1, padding: 24 }}>
{isLoading ? <Text>Loading...</Text> :
( <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'space-between'}}>
<FlatList
data={data.channel}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Text>{item.display-name}</Text>
)}
/>
</View>
)}
</SafeAreaView>
);
}
Here's a snippet of the JSON that's rendered using console.log(result)
Object {
"tv": Object {
"$": Object {
"generator-info-name": "xmltv.co.uk",
"source-info-name": "xmltv.co.uk",
},
"channel": Array [
Object {
"$": Object {
"id": "1475611020f8d0be2662c20838ddc555",
},
"display-name": Array [
"AMC from BT",
],
"icon": Array [
Object {
"$": Object {
"src": "/images/channels/1475611020f8d0be2662c20838ddc555.png",
},
},
],
},
}
But I'm unsure as to how I pull it into my flat list. Any help would be hugely appreciated! Thanks.
Try below code that might help:
import React, {useEffect, useState} from 'react';
import {FlatList, SafeAreaView, Text, View} from 'react-native';
import {parseString} from 'react-native-xml2js';
export default function App() {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
var url = 'http://www.xmltv.co.uk/feed/9437';
fetch(url)
.then((response) => response.text())
.then((responseText) => {
parseString(responseText, (_, result) => {
setData(result.tv.channel);
});
})
.catch((error) => {
console.log('Error fetching the feed: ', error);
})
.finally(() => setLoading(false));
}, []);
return (
<SafeAreaView style={{flex: 1, padding: 24}}>
{isLoading ? (
<Text>Loading...</Text>
) : (
<View
style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
}}>
<FlatList
data={data ?? []}
keyExtractor={({$: {id}}, index) => id}
renderItem={({item}) => <Text>{item['display-name'][0]}</Text>}
/>
</View>
)}
</SafeAreaView>
);
}