sujinleeme
11/11/2017 - 8:16 AM

learnPromise.js

learnPromise.js

const mapDispatchToProps = (dispatch) => {
  return {
    deleteCommentBodyContent: (id, category, parentId) => {
      dispatch(deleteCommentContent(id))
      .then(() => dispatch(getComments(parentId)))
    }
}

  
// actions
export const deleteCommentContent = (id) => {
  return (dispatch) => new Promise((res, reject) => {
    dispatch(deleteComment())
    fetch(`${baseurl}/comments/${id}`, {
      method: 'PUT', headers: headers, body: JSON.stringify({deleted: true}),
    }).then((response) => {
      if (!response.ok) {
        throw Error(response.statusText)
      }
      dispatch(deleteCommentSuccess(true))
      return response
    })
    .then((response) => response.json())
    .catch(() => dispatch(deleteCommentFailure()))
  })
}

export const getComments = (id) => {
  return (dispatch) => new Promise((resolve, reject) => {
    dispatch(fetchComments())
    fetch(`${baseurl}/posts/${id}/comments`, {headers}).then((response) => {
      if (!response.ok) {
        throw Error(response.statusText)
      }
      return response
    }).then((response) => response.json())
    .then((comments) => dispatch(fetchCommentsSuccess(comments)))
    .catch((response) => dispatch(fetchCommentsFailure()))
  })
}