nico
Published in : 2022-03-29

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.treeDataArray(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.treeDataArray(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 Date : 2022-03-29

Best answers

4

Best answers

4

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

Mohamed Atef Date : 2022-03-29

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 :)

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Warning: React.jsx: type is invalid
Publish date: 2022-05-06 | Comments: 1

Tag: React js

[solved] Expected a conditional expression and instead saw an assignment
Publish date: 2021-11-29 | Comments: 0

Tag: React js

npm install @mui/material returns error
Publish date: 2022-04-02 | Comments: 1

Tag: React js

How to use Datepick of Mui with Formik
Publish date: 2022-02-14 | Comments: 7

Tag: React js

How to get the selected object in "Autocomplete material ui"?
Publish date: 2021-12-22 | Comments: 3

Tag: React js

[solved] useEffect is repeating the request Reactjs
Publish date: 2022-04-07 | Comments: 2

Tag: React js