0
votes

Please help

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.

my React Code

    componentWillReceiveProps(nextProps){
        this.setState({appointment: nextProps.appointment })
        this.setState({responseObj: nextProps.responseObj })
     }


    render() {
        const appointment =   this.state.appointment;
        const responseObj = this.state.responseObj;
        const userId = this.props.userId;

        let content = null;
        let message = null;

         if(appointment === null ){
            content = 'loading ...';
        }

         if(appointment ===  false) 
            if(responseObj) {
                if(responseObj.data.errno === 1062){    
                    message = <div>appointment became unavailable.   </div>;
            }   
        }
        else {  
            content =  "no records ";
        }


            if(responseObj)
                if(responseObj.data.errno === 1062){    
                    message = "sorry, cannot reserve more than one appointment"   ;
                 }

        if(appointment )
        content = <SimpleMediaCard userId={userId} appointment={appointment} /> ;

        return( 
            <div>
                    {content}{ message}

            </div>
            );


    }
}


function mapStateToProps({appointment, responseObj }, ownProps){    

    return {appointment: appointment,
            responseObj: responseObj
     }
}

export default connect(mapStateToProps, mapDispatchToProps )(SavedAppointments);    

I removed unnecessary code, if you are interested in that, please let me know.

1

1 Answers

2
votes

From https://reactjs.org/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. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied"

It seems to me that you should check if the below objects are created before using them, or otherwise placing a callback inside of setState().

  const appointment =   this.state.appointment;
  const responseObj = this.state.responseObj;
  const userId = this.props.userId;