Home > Back-end >  getting undefined on fetching rss feed
getting undefined on fetching rss feed

Time:11-04

I want to randomly display some of the news from a google rss news feed using the url and the package react-native-url-preview. Im doing a fetch call on it:

const [rssFeed, setRssFeed] = useState([]);
const [shouldFetch, setShouldFetch] = useState(true);
var feed = [];

if (shouldFetch) {
 console.log("shouldFetch");
 getFeed();
 setShouldFetch(false);
}

function getFeed() {
 console.log("getFeed: "   shouldFetch);
 fetch(
   "https://news.google.com/rss/search?q=cars&hl=en-GB&gl=GB&ceid=GB:en"
 )
  .then((response) => response.text())
  .then((responseData) => rssParser.parse(responseData))
  .then((rss) => {
    console.log(typeof rss.items);
    let feedItems = rss.items;
    feed = feedItems;
    // @ts-ignore
    setRssFeed(rss.items);
  });
}

if (!shouldFetch) {
 console.log(rssFeed);
 var randomArr = [];
 while (randomArr.length < 4) {
  var r = Math.floor(Math.random() * 100);
  if (randomArr.indexOf(r) === -1) randomArr.push(r);
  // @ts-ignore
  console.log(r   " "   rssFeed[r].links[0].url);
}

}

This only works sometimes!

50% of the times I get the error: undefined is not an object (evaluating 'rssFeed[r].links'.

I thought this is beacause of the reloading in react-native and this is why i put the if check. But it has not solved it. Any ideas?

CodePudding user response:

u can use optional chaining do rss?.items u can do optional chaining like this this means if rss is present check for rss.item , in ur case do 'rssFeed?.[r]?.links'.

sometimes u get undefined error because ui get rendered before actual data is present

  • Related