Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mutating state #32

Open
pobch opened this issue Aug 9, 2020 · 1 comment
Open

Mutating state #32

pobch opened this issue Aug 9, 2020 · 1 comment

Comments

@pobch
Copy link

pobch commented Aug 9, 2020

I think you are mutating the state at the following lines:

const notes = [...state.notes]
notes[index].completed = !note.completed

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 }
@ibqn
Copy link

ibqn commented Aug 2, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants