4

I have an array that I am rendering on the render() function. Each element in the array is a HTML element that has state variables that I need to display, the HTML are displaying correctly, but the internal state variables do not update even when the rendering is happening

state = {
 array: [],
 id: 2
}

updateState() {
 this.setState({id: 4})
}

componentDidMount(){
 array = [<div> {this.state.id} </div>, <div> {this.state.id} </div>]
}

render() {
 {this.state.array.map(el => return el)}

 //assume something happens here that triggers updateState() multiple times: buttons presses, etc
}

I never see 4, it re renders but keeps the old value 2

2 Answers2

0

You are creating the array in the componentDidMount function which is only being called once when the component first renders.

You should do something like this

//create function
createArray = () => [<div> {this.state.id} </div>, <div> {this.state.id} </div>]

then use it in your code like this

{this.createArray().map(el => el)}

Hope this helps.

Shmili Breuer
  • 3,927
  • 2
  • 17
  • 26
0

You need to save the data and render again:

state = {
 id: 2
}

updateState() {
  this.setState({id: 4})
}

componentDidMount(){
  this.getElements(this.state.id)
}

getElements = (id) => {
  return [<div> {id} </div>, <div> {id} </div>]
}

render() {
 {this.getElements(this.state.id).map(el => el)}

 //assume something happens here that triggers updateState() multiple times: buttons presses, etc
}
Idan
  • 3,604
  • 1
  • 28
  • 33
  • I have something similar to this `updateState() { this.setState({array: [...this.state.array,
    {this.state.id}
    ]}) }` This gets called just fine and renders the new element, but if I manipulate this.state.id to any number independently, the array does never update the id displayed
    – Jose A Ocasio Serra Aug 08 '19 at 15:03
  • I update my answer - try this and tell me what happened now – Idan Aug 08 '19 at 15:18
  • I can't do that. On my specific issue, the array is composed of HTML elements that I cant predict how they will be. All I know is that they have a state.id that will change in the future and I need to re render that array with the re rendered value of the new id. The update of the state.id happens independently of the update or push of elements to the array. A different control will change the id. I do not have issues seeing the new elements on the array, but I do have issues seeing the updates value that exist inside the elements in the array. – Jose A Ocasio Serra Aug 08 '19 at 16:10
  • However, I noticed that if I do not use the array and just place the `
    {this.state.id}
    ` element in the render function it updates just fine when I change the state.id. I suspect the issue is that the by having an array being rendered it thinks the state.id value is a static value
    – Jose A Ocasio Serra Aug 08 '19 at 16:15