0

I m building an appointment application with react native,its my first try in RC,Using react-redux to manage the state.I need some clarification about lifecycle methods.

Details.js

class Details extends Component {
   constructor(props) {
     super(props);
     }

   componentDidMount(){
   this.props.bookingAndSuggestions(Data)
    }

    componentWillReceiveProps(nextProps){
     if( Object.keys(nextProps.bookingSuggestionStatus).length >0) {
      if(nextProps.bookingSuggestionStatus.res.data.status=='available') {
        this.setState({isAvailable:false})
      } else {
        this.setState({isAvailable:true})
      }} }

   onBookNow=()=>{
    this.props.shops(Data);
   }

Here is the deal,Initially i call react-redux action prop this.props.bookingAndSuggestions(Data) and i capture the response inside componentWillReceiveProps,and On booking this.props.shops(Data); will trigger and it also updates the componentWillrecieveprops,the logic inside the componentwillrecieveprops updates each time when props changes.What is the proper approach to deal with such situation?

Ajith
  • 587
  • 7
  • 32

1 Answers1

1

componentWillReceiveProps is called not only when the props change but also when the parent re-renders and hence whenever it is being called the state is being evaulated and set again.

You have two options

  1. If you aren't modifying the isAvailable state internally, you could simply use it from props directly.

Eg:

const isAvailable = this.props.bookingSuggestionStatus && this.props.bookingSuggestionStatus.res.data.status=='available'
  1. If you are modifying it, then you need to check if the props have changed which you can do in componentWillReceiveProps(use getDerivedStateFromProps from v16.3.0 onwards)

Eg:

componentWillReceiveProps(nextProps){
     if(!_.isEqual(nextProps.bookingSuggestionStatus, this.props.bookingSuggestionStatus) && Object.keys(nextProps.bookingSuggestionStatus).length >0) {
      if(nextProps.bookingSuggestionStatus.res.data.status=='available') {
        this.setState({isAvailable:false})
      } else {
        this.setState({isAvailable:true})
      }
     } 
}
Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
  • It would also be worth noting that `componentWillReceiveProps` is [deprecated](https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops) – Andrew Feb 17 '19 at 17:00
  • @Andrew, I think I should add it explicitly in my answer if its not clear – Shubham Khatri Feb 17 '19 at 17:19