2

I am new to react-native and I am here trying to update the state when the component is loaded. however the state is not updating.

constructor(props) {
super(props);

this.state = {
 selectedSection: 'None',
 sectionObject: { index: 0, key: ''},
 sectionIndex: 0,
 sectionArray: [],
 };
}

componentDidMount()
{
 this.setState({
 sectionObject: { index: this.state.sectionIndex, key: this.state.selectedSection},
 sectionArray: this.state.sectionArray.concat(this.state.sectionObject),
 })
 console.log('sectionObject:',this.state.sectionObject);
 console.log('section array:',this.state.sectionArray);
}

What am I doing wrong here?

fAiSaL
  • 754
  • 1
  • 10
  • 29

2 Answers2

1

Update

componentDidMount update state but this is an async so you can see updated state in render I think.

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedSection: 'None',
            sectionObject: { index: 0, key: '' },
            sectionIndex: 0,
            sectionArray: [],
        };
    }

    componentDidMount() {
        this.setState({
            selectedSection: 'Wowowowowow',
        })
    }

    render() {
        console.log(this.state.selectedSection)
        return <div>{this.state.selectedSection}</div>
    }
}

ReactDOM.render(
    <Hello name='World' />,
    document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
yanckst
  • 438
  • 4
  • 17
Talut TASGIRAN
  • 365
  • 4
  • 20
  • componentDidMount() { this.setState(prevState => ({ sectionObject: { ...prevState.sectionObject, index: this.state.sectionIndex,key:this.state.selectedSection } }), () => { console.log('sectionObject:',this.state.sectionObject); }) } – xoxo Jul 31 '18 at 06:27
  • Hey, I have provided the solution here!! It's always good to use functional form of the setState. In my case i am using prevState as a parameter and props for reference. Remember, setState call is asynchronous. In your case you are printing state in console log before the setState execution complete. So immediate after setting the state if you are printing it, you may not get the current value. instead you always get the previous state value. So, Functional form of setState excepts one more parameter where i am printing my state value in console. – xoxo Jul 31 '18 at 06:37
0

When you are trying to log in there, you can see old values. Try to log in setState callback like this setState({ key: value }, () => console.log(this.state)); . Check this out: https://reactjs.org/docs/react-component.html#setstate , https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296

Barbaros
  • 86
  • 6