Update Backend Data Using Async Action Creator

When using asynchronous action creators to update data on the backend i.e. update vote count to object,

  • make a new object, modify vote property, then send new object to backend
  • take response object and update state in reducer

Example asynchronous action creator

export const addVote = (newObject) => {
const anecdoteToChange = {
...newObject,
votes: Number(newObject.votes) + 1
}
return async dispatch => {
const newAnecdote = await anecdoteService.addVote(anecdoteToChange)
dispatch({
type: 'ADD_VOTE',
data: newAnecdote
})
}
}

Example reducer

const reducer = (state = [], action) => {
switch(action.type) {
case 'CREATE_ANECDOTE':
return [...state, action.data]
case 'INIT_ANECDOTE':
return action.data
case 'ADD_VOTE':
const changedAnecdote = action.data
return state.map(anecdote => anecdote.id !== changedAnecdote.id ? anecdote : changedAnecdote)
default:
return state
}
}