0

I'm trying to handle a promise inside a componentDidMount, i want to prevent infinite call to the promise so i want to implement an isMounted variable but i don't really understand when to set the isMounted to false to cancel the promise call.

My idea is to set the isMounted to false inside the componentWillUnmount.

So my logic is to call the promise when the component is mounted and leave the promise when the component is unmounted :

async componentDidMount() {
    if (isMounted) {
      try {
        await RegistrationService.getData();
      } catch (error) {
        console.log(error);
      }
    }
  }

  componentWillUnmount() {
    isMounted = false;
  }

I will be thankful if someone could help me to understand those to life cycle moments and when should i stop the call to the promise

Khaled Boussoffara
  • 1,567
  • 2
  • 25
  • 53

1 Answers1

1

I think a better approach would be doing something like this:

     state = {
          ready: false
     }

     async componentDidMount() {
          if (ready === false) {
               try {
                    await RegistrationService.getData();
                    this.setState({ ready: true });
               } catch (error) {
                    console.log(error);
               }
          }
     }

And regarding this:

I will be thankful if someone could help me to understand those to life cycle moments and when should i stop the call to the promise

Learn functional components and use hooks!!
It will change your life (well, your 'React' life...)

D10S
  • 1,468
  • 2
  • 7
  • 13