Mahdi Bashirpour
Mahdi Bashirpour

Reputation: 18863

how to set state in render react native

When i want to setState in render lifecycle it gives me this error

Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

changeInitial(){
   this.setState({initialLoad: false});
}

render() {
    if (this.state.initialLoad) {
        Animated.timing(this.state.listPosition, {
            toValue: 350,
            duration: 2000,
        }).start(() => this.changeInitial());
    }
 }

Upvotes: 0

Views: 5379

Answers (1)

reisdev
reisdev

Reputation: 3403

You shouldn't use setState() inside the render() method because it triggers a re-render inside the render, throwing an error. The better way to do it is inside the componentDidMount() method, like this:

changeInitial(){
   this.setState({initialLoad: false});
}
componentDidMount(){
    if (this.state.initialLoad) {
       Animated.timing(this.state.listPosition, {
           toValue: 350,
           duration: 2000,
       }).start(() => this.changeInitial());
    }
}
render() {
    // Your component template here
}

Upvotes: 4

Related Questions