ComponentDidUpdate infinite loop

Viewed 182

I'm new to React Native and I don't know if you can use componentDidUpdate this way. What I'm trying to do is call getRiderRequestDetails() within componentDidUpdate to retrieve data from Firebase anytime a new request is made. And I get an infinite loop. How can I avoid that?

componentDidUpdate(prevState) {
    getRiderRequestDetails();
   
  }

 getRiderRequestDetails = () => {
    AsyncStorage.getItem("driverId")
      .then((result) =>
        firebase
          .database()
          .ref("Ride_Request/" + result)
          .once("value")
          .then(function (snapshot) {
            if (snapshot.exists()) {
              DriverHomeContents.RiderID = snapshot.child("riderID").val();
              DriverHomeContents.RiderPickUpName = snapshot
                .child("pickUpName")
                .val();
              DriverHomeContents.RiderDropUpName = snapshot
                .child("dropOffName")
                .val();
            }
          })
          .then(
            () => {
              console.log(
                "fine " +
                  DriverHomeContents.RiderDropUpName +
                  " " +
                  DriverHomeContents.RiderPickUpName
              );
              if (!DriverHomeContents.RiderID == "") {
                this.setState({ isModalVisible: true });
              }

              firebase
                .database()
                .ref("RiderIds/" + DriverHomeContents.RiderID + "/Details")
                .once("value")
                .then(function (snapshot) {
                  DriverHomeContents.Firstname = snapshot
                    .child("firstname")
                    .val();
                  DriverHomeContents.Lastname = snapshot
                    .child("lastname")
                    .val();
                })
                .then(
                  () => {
                    console.log("fine" + DriverHomeContents.Firstname);
                  },
                  (error) => {
                  }
                );
            },
            (error) => {
              console.error("error" + error);
            }
          )
      )
      .catch((e) => console.log("err", e));
  }; 
1 Answers

https://reactjs.org/docs/react-component.html#componentdidupdate

If you read the description on above link, you will see that infinite render is bound to happen because you are updating something and then that causes the lifecycle method to run again and loop happens.

Based on what your requirement is, you can do either of these.

  • Check what other lifecycle methods fit your use-case.
  • figure out the condition for which you should not make the calls in cDidUpdate. example. checking if this.props.someProp !== prevProps.someProp then make your function call.

NOTE: The first param passed to cDidUpdate is previous props not previous state.

Related