Search code examples
react-nativefetchrss

getting undefined on fetching rss feed


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%3Aen"
 )
  .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?


Solution

  • You can use optional chaining like rss?.items.

    which means if rss is present check for rss.item.

    rssFeed?.[r]?.links
    

    Sometimes you get an Undefined Error because the UI gets rendered before the actual data is present.