0

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;
}
2
  • If, your storiesID is an array of ids, then you should only pass the array not any index in const stories = await getStoriesByID(storiesID[10]);. Please try with const stories = await getStoriesByID(storiesID); Commented Mar 3, 2018 at 3:45
  • For asynchronously derived data, always cache Promise, not the data itself. Commented Mar 3, 2018 at 10:38

1 Answer 1

1

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.