1

I have a 2D array and I need to update it in componentWillReceiveProps but it doesn't get updated.

This is my state;

this.state={
            conditionRaw:[[]]
        }

And this is componentWillReceiveProps method;

componentWillReceiveProps(nextProps){
        let rules = {conditionRaw:[[]]};
        if (nextProps.rootObject._id !== ""){
            rules["conditionRaw"] = nextProps.rootObject.conditionRaw
            this.setState({conditionRaw: rules.conditionRaw})
            console.log("DENEMEBİRLKİ", this.state.conditionRaw)
        }

    }

My nextProps come filled but I reckon I'm failing at setState.

3
  • this.setState({conditionRaw: rules.conditionRaw}, () => {console.log(this.state.conditionRaw);}); what does this say? Commented Aug 10, 2017 at 12:20
  • An empty array is returned @Nocebo Commented Aug 10, 2017 at 12:21
  • 1
    Possible duplicate of Why calling setState method doesn't mutate the state immediately? Commented Aug 10, 2017 at 12:26

1 Answer 1

2

Your console log:

console.log("DENEMEBİRLKİ", this.state.conditionRaw)

might be misleading, since setState() is asynchronous. Try this instead:

this.setState({conditionRaw: rules.conditionRaw}, () => {console.log(this.state.conditionRaw);});
Sign up to request clarification or add additional context in comments.

5 Comments

Wow, yeah it returns filled now.So this means I updated my state successfully, right?
Yeah, setState is asynchronous. Always use this callback function to check wheter or not it changed
Thanks a lot! I can't mark your answer now. After 10 minutes, I'll do it.
No problem! Thanks
@BurakULU would you be so kind to mark my answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.