Most of the time, it runs with no error, but sometimes, it doesn't run at all and gives out: How do I resolve TypeError: undefined is not an object (evaluating 'rss.items[0].title')
This is my code, I use react-native-rss-parser
(https://www.npmjs.com/package/react-native-rss-parser) to parse my rss feed:
class HomeScreen extends React.Component {
state = {
feed: [],
title0: [],
title1: []
};
componentDidMount() {
return fetch("https://vnexpress.net/rss/tin-moi-nhat.rss")
.then(response => response.text())
.then(responseData => rssParser.parse(responseData))
.then(rss => {
this.setState(prevState => ({
...prevState,
feed: rss,
title0: rss.items[0].title,
title1: rss.items[1].title
}));
});
}
render() {
const Feeds = shuffleArray([
{
pic: require("../assets/images/image.jpg"),
title: Object.keys(this.state.title0).map(k => this.state.title0[k]),
caption: "caption"
},
{
pic: require("../assets/images/image.jpg"),
title: Object.keys(this.state.title1).map(k => this.state.title1[k]),
caption: "caption"
}
]);
return (
<SafeAreaView>
<Swiper
cards={Feeds}
renderCard={Card}
infinite
backgroundColor="white"
cardHorizontalMargin={0}
stackSize={2}
/>
</SafeAreaView>
);
}
}
const Card = ({ pic, title, caption }) => (
<Tile
imageSrc={pic}
activeOpacity={1}
title={title}
caption={caption}
featured
key={title}
/>
);
export default HomeScreen;
UPDATE
Console.log(rss) result (It does contain items):
Object {
"authors": Array [],
"categories": Array [],
"copyright": undefined,
"description": "VnExpress RSS",
"image": Object {
"description": undefined,
"height": undefined,
"title": "Tin nhanh VnExpress - Đọc báo, tin tức online 24h",
"url": "https://s.vnecdn.net/vnexpress/i/v20/logos/vne_logo_rss.png",
"width": undefined,
},
"items": Array [],
"itunes": Object {
"authors": Array [],
"block": undefined,
"categories": Array [],
"complete": undefined,
"explicit": undefined,
"image": undefined,
"newFeedUrl": undefined,
"owner": Object {
"email": undefined,
"name": undefined,
},
"subtitle": undefined,
"summary": undefined,
},
"language": undefined,
"lastPublished": "Sat, 30 Nov 2019 21:28:12 +0700",
"lastUpdated": undefined,
"links": Array [
Object {
"rel": "",
"url": "https://vnexpress.net/rss/tin-moi-nhat.rss",
},
],
"title": "Tin mới nhất - VnExpress RSS",
"type": "rss-v2",
}
you cant acsess rss.items[0].title as rss.items[0] is undefined just add a check like that before trying to get the title
componentDidMount() {
return fetch("https://vnexpress.net/rss/tin-moi-nhat.rss")
.then(response => response.text())
.then(responseData => rssParser.parse(responseData))
.then(rss => {
this.setState(prevState => ({
...prevState,
feed: rss,
title0: rss.items[0]? rss.items[0].title:'',
title1: rss.items[1]? rss.items[1].title:''
}));
});
}