How to return an array received from fetching api data in a .then statement?

*爱你&永不变心* 提交于 2019-12-24 18:58:31

问题


I'm trying to export an array inside a .then statement but its not working. I have no clue how to make it work otherwise. Actually I'm just trying to set my initial state in redux to this static data I am receiving from the movie database api.

import { API_URL, API_KEY } from '../Config/config';

const urls = [
`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`,
`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=2`,
]

Promise.all(urls.map(items => {
return fetch(items).then(response => response.json())
}))

.then(arrayOfObjects => {
var arr1 = arrayOfObjects[0].results;
var arr2 = arrayOfObjects[1].results;
export var movieData = arr1.concat(arr2);   
}
)

回答1:


It's not clear where this code is in relation to your state/reducer, but ideally you should be using action creators to deal with any API calls and dispatch state updates, and those action creators can be called from the component.

So, initialise your state with an empty array:

const initialState = {
  movies: []
};

Set up your reducer to update the state with MOVIES_UPDATE:

function reducer(state = initialState, action) {
  const { type, payload } = action;
  switch (type) {
    case 'MOVIES_UPDATE': {
      return { ...state, movies: payload };
    }
  }
}

You can still use your function for fetching data:

function fetchData() {
  return Promise.all(urls.map(items => {
    return fetch(items).then(response => response.json());
  }));
}

..but it's called with an action creator (it returns a function with dispatch param), and this action creator 1) gets the data, 2) merges the data, 3) and dispatches the data to the store.

export function getMovies() {
  return (dispatch) => {
    fetchData().then(data => {
      const movieData = data.flatMap(({ results }) => results);
      dispatch({ type: 'MOVIES_UPDATE', payload: movieData });
    });
  }
}

And it's called from within your component like so:

componentDidMount () {
  this.props.dispatch(getMovies());
}



回答2:


You can try with a function. like this:

import { API_URL, API_KEY } from '../Config/config';

export const getMovies = () => {
   const urls = [
   `${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`,
   `${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=2`,
  ]

  const promises = urls.map(url => {
    return new Promise((reject, resolve) => {
     fetch(url).then(res => res.json())
      .then(res => resolve(res.results))
    })
  })

  return Promise.all(promises)
}

// other file

import {getMovies} from 'YOUR_API_FILE.js';

getMovies().then(moviesArr => {
   // your business logics here
})



回答3:


You can modify the code as below:

import { API_URL, API_KEY } from '../Config/config';
let movieData='';

exports.movieData = await (async function(){

const urls = [
`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`,
`${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=2`,
];

const arrayOfObjects = await Promise.all(urls.map(items => {
return fetch(items).then(response => response.json())
}));

 return arrayOfObjects[0].results.concat(arrayOfObjects[1].results);
 })();


来源:https://stackoverflow.com/questions/57523342/how-to-return-an-array-received-from-fetching-api-data-in-a-then-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!