2

I'm using React and i need to store some Api requests into variables so that i could do some modifications.

I want to do something like this :

function getMovies() {

var moviesArr = '';
return fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=4344343' +
'd61a2e5')
.then((response) => response.json())
.then((json) => moviesArr = json);

  }

 const currentMoviesArray = getMovies() // Then to recieve the movies data

So the const currentMoviesArray will finally bring me back the fetched data

RoyBarOn
  • 919
  • 3
  • 24
  • 63
  • Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Andrew Li Oct 08 '18 at 00:20

2 Answers2

0

Instead of storing it to a varibale. You can set the response to one state variable, so that you can use it every where in component.

function getMovies() {
  return fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=4344343' +
  'd61a2e5')
 .then((response) => response.json())
 .then((json) => this.setState({moviesArr:json});
}
user8599269
  • 241
  • 1
  • 11
-1

The function getMovies() returns a promise. so you can either set the values of currentMoviesArray from within the then() handler, or refactor your function with async/await which waits for a promise to settle and return a result, see both options below:

Option 1:

const currentMoviesArray = [];

function getMovies() {
  fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=4344343' +
  'd61a2e5')
  .then((response) => response.json())
  .then((movies) => currentMoviesArray.push(movies));
}

Option 2:

async function getMovies() {
  await fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=4344343' + 'd61a2e5')
    .then((response) => response.json());
}

const currentMoviesArray = getMovies();
Sergio Alen
  • 716
  • 5
  • 8
  • Option 1 suffers the same fate as the OP's code and still *returns a promise*. Option 2 **also returns a promise**, which you must await again to get the actual JSON. You also have a useless callback `then((movies) => movies)` – Andrew Li Oct 08 '18 at 11:31
  • Sergio Alen - i get an empty array in Option1 - but when i open the array in the console - i get the result - but if i do currentMoviesArray[0].results - i get undefined.... – RoyBarOn Oct 09 '18 at 19:39