1

I'm having problems with a checkbox in my code in two areas, The first one, in my reducer, I want to see if the current state of the checkbox is "true" or "false" but I keep getting syntax errors on the if.

const initialState = {
  viewCheckbox: false
}
export default (state = initialState, action) => {
    switch (action.type){
        case 'VIEW_CHECKBOX':
            return {
                ...state
                if (viewCheckbox == false) {
                    viewCheckbox: true
                } else {
                    viewCheckbox: false
                }
            }
        default:
            return: state
    }
}

My second problem is with the mapDispatchToProps, I'm using a table to create multiple checkboxes and I want to be able to differentiate each one of them by ID, and when I do it like this, it checks every checkbox on the table.

const mapDispatchToProps = (dispatch) => ({
    handleViewCheckbox: id => ev => {
      dispatch(viewCheckboxSubmit(id, ev.target.checked))
    }
})

And when I create the checkbox I do it like this:

<FormControlLabel
    control={
        <Checkbox
            checked={checkedView}
            onChange={handleViewCheckbox(n.id,checkedView)}
         />
     }
     label='See'
/>
1
  • This post is super old, but your reducer isn't pure because output depends on external state (whether or not viewCheckbox is checked). Redux reducers must be pure by design, so a better option is to have separate check and uncheck actions as opposed to one toggle action. Commented May 6, 2020 at 14:40

1 Answer 1

3

You can't do an if inside an object like that. You can use the spread operator as you have done, add solo variables in which the key matches the variable you want to use, or you can add keys directly. try something like this:

case 'VIEW_CHECKBOX':
   return {
       ...state,
       viewCheckbox: !viewCheckbox
   }

They're all going to toggle on and off because you're using the same bit of state to manage whether or not it is checked. If you want to go about it this way, you could try storing whether each one is checked in an object and just keep updating that.

{
  checkboxid1: false,
  checkboxid2: false,
  checkboxid3: true  // checked
}

then the checked prop for your checkbox component would look like..

checked={this.props.isChecked[n.id]}

assuming you pulled that object out in mapStateToProps and called it isChecked

Sign up to request clarification or add additional context in comments.

Comments

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.