Search code examples
reactjssetstatereactstrap

Setstate not updating in CustomInput type='checkbox' handler


This is the render method, how i am calling the handler and setting the reactstrap checkbox.

    this.state.dishes.map(
                    (dish, i) => (
                      <div key={i}>
                          <CustomInput
                            type="checkbox"
                            id={i}
                            label={<strong>Dish Ready</strong>}
                            value={dish.ready}
                            checked={dish.ready}
                            onClick={e => this.onDishReady(i, e)}
                          />

                        </div>))

The handler for the onClick listener, I've tried with onchange as well but it apears that onchange doesnt do anything, idk why?

  onDishReady = (id, e) => {
    console.log(e.target.value)
    var tempArray = this.state.dishes.map((dish, i) => {
      if (i === id) {


        var temp = dish;
        temp.ready = !e.target.value
        return temp
      }
      else {
        return dish
      }
    })
    console.log(tempArray)
    this.setState({
      dishes: tempArray

    });

  }

Solution

  • The event.target.value isn't the "toggled" value of an input checkbox, but rather event.target.checked is.

    onDishReady = index => e => {
      const { checked } = e.target;
      this.setState(prevState => {
        const newDishes = [...prevState.dishes]; // spread in previous state
        newDishes[index].ready = checked; // update index
        return { dishes: newDishes };
      });
    };
    

    The rendered CustomInput reduces to

    <CustomInput
      checked={dish.ready}
      id={i}
      label={<strong>DishReady</strong>}
      onChange={this.onDishReady(i)}
      type="checkbox"
    />
    

    No need to pass in a value prop since it never changes.

    Note: Although an onClick handler does appear to work, semantically it isn't quite the correct event, you want the logic to respond to the checked value of the checkbox changing versus a user clicking on its element.

    Edit checkbox array toggle demo