waveform/src/store/reducers/comments.js
2019-04-13 18:24:41 -04:00

100 lines
2.4 KiB
JavaScript

import axios from 'axios'
import {addedVote} from './votes'
// ACTION TYPES
const GOT_ALL_COMMENTS = 'GOT_ALL_COMMENTS'
const ADD_COMMENT = 'ADD_COMMENT'
const UPVOTED_COMMENT = 'UPVOTED_COMMENT'
const DOWNVOTED_COMMENT = 'DOWNVOTED_COMMENT'
const initialComments = []
// ACTION CREATORS
export const gotAllComments = comments => ({
type: GOT_ALL_COMMENTS,
comments,
})
export const addedComment = comment => ({
type: ADD_COMMENT,
comment,
})
export const upvotedComment = comment => ({
type: UPVOTED_COMMENT,
comment,
})
export const downvotedComment = comment => ({
type: DOWNVOTED_COMMENT,
comment,
})
// THUNK CREATORS
export const fetchAllComments = () => async dispatch => {
try {
const res = await axios.get('/api/comments')
const comments = res.data
dispatch(gotAllComments(comments))
} catch (err) {
console.error(err)
}
}
export const addComment = comment => async dispatch => {
try {
const res = await axios.post('/api/comments', comment)
dispatch(addedComment(res.data))
} catch (err) {
console.error(err)
}
}
export const upvoteComment = (userId, commentId) => async dispatch => {
console.log('REDUCER UPVOTECOMMENT', userId, commentId)
try {
const {data} = await axios.post(`/api/comments/${commentId}/upvote`, {userId})
console.log('the votesum should have changed', data)
dispatch(upvotedComment(data.comment))
dispatch(addedVote(data.vote))
} catch (err) {
console.error(err)
}
}
export const downvoteComment = (userId, commentId) => async dispatch => {
try {
const {data} = await axios.post(`/api/comments/${commentId}/downvote`, {userId})
console.log('the votesum should have changed', data)
dispatch(downvotedComment(data.comment))
dispatch(addedVote(data.vote))
} catch (err) {
console.error(err)
}
}
// export const addVote = vote => async dispatch => {
//
// try {
// const res = await axios.get(`/api/comments/${id}`)
// dispatch(addedVote(res.data))
// } catch (err) {
// console.error(err)
// }
// }
// REDUCER
const commentReducer = (comments = initialComments, action) => {
switch (action.type) {
case GOT_ALL_COMMENTS:
return action.comments
case ADD_COMMENT:
return comments.concat(action.comment)
case UPVOTED_COMMENT: {
const oldComments = comments.filter(comment=>comment.id !== action.comment.id)
return oldComments.concat(action.comment)
}
default:
return comments
}
}
export default commentReducer