zmaqutu
zmaqutu

Reputation: 3

How to update the state of a string using previous state

I am new to React and Javascript. I have a class component with a constuctor and function that look like this:

class MyComponent extends Component {
constructor(props) {
    super(props)
    this.state = {
       HTMLTable : ""  
    }
createGrid ()
{
    for(let row = 0; row <= 20;row++)
    {
        let currentHTMLRow = `<tr id = "Row ${row}">`;
        for(let col = 0; col < 50; col++)
        {
            let newNodeId = `${row}_${col}`;
            let NodeClass = "unvisited";
            currentHTMLRow = currentHTMLRow +`<td id = "${newNodeId}" class = "${NodeClass}"></td>`
        }
        this.state.HTMLTable += `${currentHTMLRow}</tr>`;
    }
    let chart = document.getElementById("grid");
    chart.innerHTML = this.state.HTMLTable;
}
}

This produces the desired effect but I have been warned against changing the value of the state like this

this.state.HTMLTable += `${currentHTMLRow}</tr>`;

*How do I change the state of the HTMLTable String using setState() everytime the loop iterates such that: this.state.HTMLTable += ${currentHTMLRow}</tr>; *

Upvotes: 0

Views: 1715

Answers (3)

k-wasilewski
k-wasilewski

Reputation: 4663

The simplest way to do it:

this.setState({
    HTMLTable: this.state.HTMLTable+=currentHTMLRow
});

Upvotes: 0

assembler
assembler

Reputation: 3300

the way you change the state using a previous state is this:

this.setState(prevState => {
   return {HTMLTable: prevState.HTMLTable + whatever you want};
});

Upvotes: 1

Rinkesh Golwala
Rinkesh Golwala

Reputation: 1049

You should not use the setState function in the loop in React. By looking at your code, you don't need a state variable inside your loop. What you can do is to have a local variable, update it inside the loop, and at the end store it back to the state.

class MyComponent extends Component {
constructor(props) {
    super(props)
    this.state = {
       HTMLTable : ""  
    }
createGrid () {
    let HTMLTable = ""; // Use local varibale
    for(let row = 0; row <= 20;row++)
      {
          let currentHTMLRow = `<tr id = "Row ${row}">`;
          for(let col = 0; col < 50; col++)
          {
              let newNodeId = `${row}_${col}`;
              let NodeClass = "unvisited";
              currentHTMLRow = currentHTMLRow +`<td id = "${newNodeId}" class = "${NodeClass}"></td>`
          }
          HTMLTable += `${currentHTMLRow}</tr>`;
      }
      this.setState({HTMLTable}); // Store it back to the state.
      let chart = document.getElementById("grid");
      chart.innerHTML = HTMLTable;
    }
}

Upvotes: 0

Related Questions