0

I have to call API when the user stops typing and it is working perfectly fine. And I have to mount when the enter key is pressed. I made a Mock Component here which does this.

But, when the component is unmounted it shows the error Cannot call setState on an unmounted component. Previously I handled this error with this.isMounted. Now I was trying to handle it using promise cancelling in componentWillUnmount as mentioned in the React Blog.

this.cancellablePromise = makeCancelable(getSearchResults(word));

      this.cancellablePromise.promise
        .then(res => {
          console.log({ res });
          this.setState({ values: res });
        })
        .catch(err => console.log("error", err));
      console.log("in data ", this.cancellablePromise);
    }

The cancellablePromise gets assigned after the promise got resolved. So there is a null object in componentWillUnMount for cancellablePromise instance.

noName94
  • 3,783
  • 1
  • 16
  • 32

2 Answers2

0

Looks like you just need to do the following thing:

myAwesomeMethod = () => {
    this.cancellablePromise = makeCancelable(getSearchResults(word));
    this.cancellablePromise
        .then(...)
        .catch(...)
}

componentWillUnmount() {
    this.cancellablePromise && this.cancellablePromise.cancel();
}

this.cancellablePromise will be undefined only in the case when you unmount your component before the call of the method with promise call.

steppefox
  • 1,784
  • 2
  • 14
  • 19
0

The issue is that your handleChange method calls debouncedGetSearchResult, but you are initializing this.cancellablePromise in getSearchResult. This leaves a 500ms window for the unmount to happen before you have initialized this.cancellablePromise.

You need to rework this so that the debouncing is part of the cancelable promise rather than prior to it.

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198