Aswin Mohan
Aswin Mohan

Reputation: 1012

Unhandled Promise Rejection while using object response from React Native Fetch

I'm currently building a Hacker News Reading Client in React Native using their Official API

I want to display the top stories of the day. So first I get the id's of the top posts for the day and then use those id's to fetch the stories.

But when I run this the promise gets rejected with:

ids.map is undefined

How can I fix this?

FeedScreen.js

import { getTopStoriesID, getStoriesByID } from '../../hacknews-api';

class FeedScreen extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loaded: false,
      stories: [],
    };
  }

  async componentDidMount() {
    const storiesID = await getTopStoriesID();
    const stories = await getStoriesByID(storiesID[10]);

    this.setState({ stories });
  }

  render() {
    return <Text>{this.state.stories}</Text>;
  }
}

export default FeedScreen;

hacknews-api.js

const BASE_URL = 'https://hacker-news.firebaseio.com/v0';

export const getTopStoriesID = async () => {
  const res = await fetch(BASE_URL + '/topstories.json');
  const storiesID = await res.json();

  return storiesID;
};

export const getStoriesByID = async (ids) => {
  const res = await Promise.all(ids.map(async (id) => {
    const res = await fetch(BASE_URL + `/item/{id}.json`)
    const story = await res.json();

    return story;
  }));
  
  const stories = await res.json();
  return stories;
}

Upvotes: 0

Views: 323

Answers (1)

bennygenel
bennygenel

Reputation: 24660

You can use Array.prototype.map() on an array and not an object.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Example

export const getStoriesByID = async (ids) => {
  // check if the argument is defined and its an Array
  if(ids && ids.constructor === Array) {
    // do something with array of ids, for example do a map()
  } else {
    // do something otherwise
  }
}

Upvotes: 1

Related Questions