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
  • 795,719
  • 175
  • 1,089
  • 1,143
Strahinja Ajvaz
  • 2,521
  • 5
  • 23
  • 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
  • 21,981
  • 30
  • 95
  • 142
Alexander Vitanov
  • 4,074
  • 2
  • 19
  • 22