4

Updating the JSON state using setState is not happening

1.I want to change the particular quantity value in the JSON, for this I wrote an IncrementHandler method to a tag and implemented the function but it is not updating my main state

2.I implemented the setState method inside the function for updating the state.

import React, { Component } from 'react';

export default class App extends Component {
  state = {
    value: 0,
    students: [
      {
        item: 'salad',
        qty: 2,
        department: 'Information Technology',
        rollno: '123'
      },
      {
        item: 'cheese',
        qty: 2,
        department: 'Computer Engineering',
        rollno: '456'
      },
      {
        item: 'meat',
        qty: 2,
        department: 'Information Technology',
        rollno: '789'
      }
    ]
  };

  render() {
    const IncrementHandler = (type) => {
      if (type === 'salad') {
        this.setState((prevState) => ({
          qty: this.state.students[0].qty + 1
        }));
      }
    };

    return (
      <div>
        <div>
          <div>
            <table border="2">
              <tbody>
                <tr>
                  <th>Item</th>
                  <th>Quantity</th>
                  <th>Button</th>
                </tr>
                {this.state.students.map((item, i) => (
                  <tr key={i}>
                    <td>{item.item}</td>
                    <td>{item.qty}</td>
                    <td onClick={() => IncrementHandler(item.item)}>click</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    );
  }
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181

1 Answers1

3

Issues

You aren't updating the nested state in the student array. You are generating a new root state key qty.

this.setState(prevState => ({
  qty : this.state.students[0].qty + 1
}))

Solution

Shallow copy the student array to create a new array reference, and shallow copy the element you want to update within the array. General note about updating nested state in react, you need to shallow copy any object you are updating since React uses shallow object equality to reconcile differences.

const IncrementHandler = item => {
  this.setState(prevState => ({
    students: prevState.students.map(student =>
      student.item === item
        ? {
            ...student,
            qty: student.qty + 1,
          }
        : student,
    ),
  }));
};

Note: You should probably also declare this callback outside the render function. It will still work defined there in the render method, but it goes against convention.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181