full-stack-serverless-code
full-stack-serverless-code copied to clipboard
Mutating state
I think you are mutating the state at the following lines:
https://github.com/dabit3/full-stack-serverless-code/blob/44c4eb269757d412f8fb27a9cee4a7bb79bf768b/graphql/src/App.js#L83-L84
Since each note is an object, setting notes[index].completed property is mutating the note object. Instead, we should create a new note object like this:
const notes = [...state.notes]
notes[index] = { ...state.notes[index], completed: !note.completed }
I also did not like the way notes were updated.
My solution was to use map to obtain an updated copy of notes, i.e.
let completed = undefined
const notes = state.notes.map((note) => {
if (note.id === id) {
completed = !note.completed
return { ...note, completed }
}
return note
})
Thus, the complete updateNote function looks
const updateNote = async ({ id }) => {
let completed = undefined
const notes = state.notes.map((note) => {
if (note.id === id) {
completed = !note.completed
return { ...note, completed }
}
return note
})
try {
await API.graphql({
query: UPDATE_NOTE,
variables: {
input: { id, completed },
},
})
console.log('successfully updated note')
} catch (error) {
console.log('error: ', error)
}
dispatch({ type: 'SET_NOTES', notes })
}
The entire example can be found here, if some one is interested.