0
showAllPics(docid){

        console.log(docid)
        var newSelected = Object.assign({},this.state.CompetitorPhotos);

        console.log("b4-->",newSelected[docid]['display']);
        newSelected[docid]['display'] = true;
        console.log("after -->",newSelected[docid]['display'],newSelected);

        console.log(newSelected,this.state.CompetitorPhotos)

        this.setState({ CompetitorPhotos: newSelected },function(){
            console.log(newSelected,this.state.CompetitorPhotos)
        });

    }

I am trying to update 'display' property in a nested property of reactjs state. The following code fails...What am i doing wrong ..

    console.log("after -->",newSelected[docid]['display'],newSelected);
    results in "after -->",true, newSelected.docid.display remains false
2
  • Object.assign({}) does not deep copy, so you're basically mutating your state when doing newSelected[docid]['display'] = true; You could however use something like : cloneDeep from lodash in order to update your state as needed lodash.com/docs/4.17.4#cloneDeep Commented Aug 24, 2017 at 7:29
  • can you make a jsbin / jsfiddle with some dummy data Commented Aug 24, 2017 at 8:01

3 Answers 3

1

You can update nested state with ... Just look at this question: react set state in for nested state

return {
    ...state,
    fetching: false,
    fetched: true
}
Sign up to request clarification or add additional context in comments.

Comments

0

Important thing to notice here (from https://facebook.github.io/react/docs/react-component.html#setstate):

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

Comments

0

Sorry for answering a second time. Here's an example how to update a nested store in React:

    this.setState({test: {one: 'asdasdasd'}}, () => {
        let { test } = this.state
        const second = {two: 'zwei'}
        Object.assign(test, second)
        this.setState({
            test,
        }, () => {
            console.log(this.state)
        })
    })

Comments

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.