3

I am new to Typescript React and also to Ionic framework.

I am using JS FETCH API and fetching data from a third-party. Now, i'd like to get the fetched data and return it to my DOM but I don't know on how to access the fetched data outside my Fetch.

please enlighten me.. thanks

function getData() {
fetch('URL')
.then(response => {
return response.json();
}).then(data_from_fetched => {
let data = data_from_fetched.results;
return data;
}}

let data = getData()
console.log(data); //undefined

let data = getData() console.log(data); //undefined

I tried this async too..

async function getData() {
fetch('url')
.then(response => {
return response.json();
}).then(data_from_fetched => {
console.log(data_from_fetched)
let data = data_from_fetched.results;
return data;        
})

}

getData().then(data => console.log(data));

or this..

function getData() {
fetch('url')
.then(response => {
return response.json();
}).then(data_from_fetched => {
console.log(data_from_fetched)
let data = data_from_fetched.results;
return data;        
})
}

let data= getData();

// and display it on my DOM

{movies.map(movie => movie){
let title = <IonCardTitle>{movie.title}</IonCardTitle>}}
kch10
  • 55
  • 2
  • 8

1 Answers1

4

You need to return a promise from your getData function, you can do it as this

function getData() {
  return new Promise((resolve, reject) => {
    fetch('URL')
     .then(response => {
       return response.json();
      }).then(data_from_fetched => {
         let data = data_from_fetched.results;
         resolve(data);
   }
})    
}

Then you can call it as this

let movies = '';
getData().then(data => {
  movies = data
});

Hope it helps

ibtsam
  • 1,620
  • 1
  • 10
  • 10
  • It works!! thank you so much and last question, how can I access the arrays inside PromiseValue? tried this code getData().then(data => { return data.PromiseValue; }); const movies = getData(); console.log(movies) but error. – kch10 Nov 09 '19 at 08:57
  • I have edited the answer to save response in variable, but if you are using react I would suggest saving it to state – ibtsam Nov 09 '19 at 09:02
  • since fetch returns a Promise, wrapping a `fetch` call in a Promise constructor is an anti-pattern - you've also lost the ability to handle errors, and if there is an error, that promise you return will be pending forever - – Bravo Nov 09 '19 at 09:05
  • 1
    here's how getData **should** be written properly: `const getData = () => fetch('URL').then(response => response.json()).then(({results}) => results); ` – Bravo Nov 09 '19 at 09:07
  • I'm getting unknown type.. :O – kch10 Nov 09 '19 at 09:17
  • @Bunny10100 - surely the error has more to it than "unknown type" – Bravo Nov 09 '19 at 09:19
  • how am I supposed to access the values inside results? – kch10 Nov 09 '19 at 09:25