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
abdul
  • 1,531
  • 1
  • 14
  • 29
Vivek
  • 176
  • 1
  • 8
  • 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 https://lodash.com/docs/4.17.4#cloneDeep – Daniel Andrei Aug 24 '17 at 07:29
  • can you make a jsbin / jsfiddle with some dummy data – Nitish Phanse Aug 24 '17 at 08:01

3 Answers3

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
}
emma93
  • 177
  • 2
  • 12
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.

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)
        })
    })
emma93
  • 177
  • 2
  • 12