user image

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.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 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

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

Tag: React js

Reload browser window using Reactjs?
Publish date: 2022-02-08 | Comments: 4

Tag: React js

Could not be processed as an image because it has an invalid content type
Publish date: 2021-12-08 | Comments: 0

Tag: React js

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

Tag: React js