4

I have the following snippet of code

export const fetchPosts = () => async dispatch => {
  const res = await axios.get(`${url}/posts`, { headers: { ...headers } });
  console.log(res.data);
  let posts = res.data.map(p => (p.comments = fetchComments(p.id)));
  console.log(posts);
  dispatch({ type: FETCH_POSTS, payload: res.data });
};

export const fetchComments = id => async dispatch => {
  console.log(id)
  const res = await axios.get(`${url}/posts/${id}/comments'`, {
    headers: { ...headers }
  });
  console.log("id", id);
  return res.data;
};

when i console log the posts, i get 2 functions returned. what is the proper way in which i should call the fetch comments for this function to return me the desired value?

Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
Strahinja Ajvaz
  • 2,181
  • 5
  • 20
  • 38
  • 1
    Why is `fetchComments` taking a `dispatch` parameter that it's never using? Drop that and you'd get two *promises* instead of functions - promises which you [then could await](https://stackoverflow.com/q/37576685/1048572) – Bergi Oct 27 '17 at 10:07

1 Answers1

3

Add this:

const postsResult = await Promise.all(posts)
4b0
  • 20,627
  • 30
  • 92
  • 137
Alexander Vitanov
  • 3,916
  • 2
  • 18
  • 22