Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array.push in React Native but array remains empty?

I am fairly new to React Native, so bear with me.

I use the following code to get RSS items form a feed.

fetch("https://feed.podbean.com/omroepvoeren/feed.xml")
  .then((response) => response.text())
  .then((responseData) => rssParser.parse(responseData))
  .then((rss) => {
    for (var item of rss.items) {
      console.log(item.title);
    }
  });

This seems to work. All titles are shown in the console.
But when I change the code to this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var listOfTitles = [];
fetch("https://feed.podbean.com/omroepvoeren/feed.xml")
  .then((response) => response.text())
  .then((responseData) => rssParser.parse(responseData))
  .then((rss) => {
    for (var item of rss.items) {
      listOfTitles.push(
        <View>
          <Text>{item.title}</Text>
        </View>
      );
    }
  });

console.log(listOfTitles); 

The array remains empty. Array [] What is going wrong here?

>Solution :

var listOfTitles = [];
    fetch("https://feed.podbean.com/omroepvoeren/feed.xml")
      .then((response) => response.text())
      .then((responseData) => rssParser.parse(responseData))
      .then((rss) => {
        for (var item of rss.items) {
          listOfTitles.push(
            <View>
              <Text>{item.title}</Text>
            </View>
          );
        }

        console.log(listOfTitles); 
      });
const response = await fetch("https://feed.podbean.com/omroepvoeren/feed.xml");         
const responseText = await response.text();                                                                    const rss = rssParser.parse(responseText);                                                                      
for (var item of rss.items) {
    listOfTitles.push(
        <View>
             <Text>{item.title}</Text>
        </View>
    );
}                                                                                                                                          console.log(listOfTitles);

It would pass fetch function, but you are adding items after calling api done. So it would be empty array, if you want, you can use "await" too.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading