-2

how to update nested state in reactjs, such as I have an Array of an object of course

state = {
    courses: [
      { id: 1, coursename: "CSS3", like: 25, dislike: 0 },
      { id: 2, coursename: "Javascript", like: 45, dislike: 0 },
      { id: 3, coursename: "ReactJS", like: 294, dislike: 0 }
    ]
  };

now i want to update like on the particular course only on onClick , after updating it should be 26 . and again if i click it should decremented by 1.

learner62
  • 520
  • 3
  • 10
  • 26

1 Answers1

1

In your handleLike method, you can map the courses and update the like field of the given course like this:

  handleLike = id => {
    console.log("id", id);
    const updatedCourses = this.state.courses.map(c => {
      if (c.id === id) {
        return {
          ...c,
          like: c.like + 1
        };
      } else {
        return c;
      }
    });

    this.setState({
      courses: updatedCourses
    });
  };
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54