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;
}
storiesIDis anarray of ids, then you should only pass the array not any index inconst stories = await getStoriesByID(storiesID[10]);. Please try withconst stories = await getStoriesByID(storiesID);