nico

29 Mar 2022

React Component setState doesn't update my property

React js

Hello my state is defined in my react class component 

constructor(props) {
 super(props);
 
 this.state = {
 searchString: '',
 searchFocusIndex: 0,
 nodeClicked: '',
 treeData: props.data.treeData
 };

The treeData is

this.state.treeData
Array(1) [Object]
 [[Prototype]]: Array(0)
 length: 1
 0: Object {title: "xxx", subtitle: "yyy", children: Array(1), …}
 __proto__: Array(0)

In the event handler I try

handleFilter = (e) => {
 console.dir(this.state.nodeClicked);
 this.setState(
 { treeData: [this.state.nodeClicked] });
 };

with [this.state.nodeClicked]

[this.state.nodeClicked]
Array(1) [Object]
 [[Prototype]]: Array(0)
 length: 1
 0: Object {title: "zzz", children: Array(1), expanded: true}
 __proto__: Array(0)

render is called again but this.state.treeData is unchanged…
 

this.state.treeData
Array(1) [Object]
 [[Prototype]]: Array(0)
 length: 1
 0: Object {title: "xxx", subtitle: "yyy", children: Array(1), …}
 __proto__: Array(0)

Can you tell me why?
Thanks

Comments

nico

29 Mar 2022

I solved the problem it was because I updated this state in 
 


 static getDerivedStateFromProps(props, current_state) {
 
 ...
 return { treeData: props.data.treeData }
 }

which overrides my new treeData state with previous treeData

Replies

Mohamed Atef

29 Mar 2022

githubgithubgithub

I was going to suggest doing it this way because React component is working using Async/await so some things might need to be passed directly to the function to stay up to date
Good Luck :)

© 2024 Copyrights reserved for web-brackets.com