0

Trying to create a really simple redux todo, almost there but got stuck on one thing.

export const completeTodo = (todo) => ({
  type: 'COMPLETE_TODO',
  data: {
    name: todo,
    complete: !todo.complete
  }
})

however, struggling to get the reducer working as I can't work out how to determine the exact object im working on

reducer:

case 'COMPLETE_TODO': {
   const chore = { ...state.chores, complete: action.data.complete}
   return { ...state.chores, chore };
}

and initialState is:

const initialState = {
  chores: [{name: 'cleaning', complete: false}]
}

obviously when i click my button is should be wired up so it can change the complete boolean to the opposite but only for that one todo

1
  • Either identify the todo based on its index in the array, or give it a unique ID and search the array for that. Have you read the official Redux tutorial? It shows exactly how to do this. Commented Feb 2, 2018 at 14:34

1 Answer 1

1

Since you have an array you need to replace it with a new one

case 'COMPLETE_TODO': {
      return {
        ...state,
        chores: state.chores.map(chore => 
         chore.name === action.data.name
         ? {...chore, complete: true /* or !chore.complete if you want toggle like behaviour*/}
         : chore)
      };
    }

and in your action creator

export const completeTodo = (todo) => ({
  type: 'COMPLETE_TODO',
  data: {
    name: todo.name // assumning names are unique
  }
})
Sign up to request clarification or add additional context in comments.

2 Comments

this is what I thought but it's not toggling it or throwing an error :/
@TheWalrus Glad I could help. Actually I have a typo in my code it should be complete not completed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.