1

I use Navigator component in my app, to render content of route i do http request with fetch to get data from server.

componentDidMount () {
    fetch(url).then((res) => {
         this.setState({data: res});
    });
}

Problem I have is that sometimes fetch closure fires when component that called it is no longer mounted so I keep getting error that i'm trying to update unmounted component. This happens if you move quickly between routes. Is there a way to terminate closure execution if component is dismounted?

2 Answers 2

4

On mounting your component you should start fetch request which gives Promise and store it.

Then you can make this Promise a CancelablePromise and cancel the promise on unmounting the component.

Here you can read how to make CancelablePromise.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for answer. What I actually had in my closure was fetch, than sort of received data, and setState at and. This give me idea to break this on 3 promises so i can even skip sorting if component is already dismounted on second part.
0

You should check whether the component is mounted before settings the state.

componentDidMount() {
    this.isMounted = true;
    fetch(url).then((res) => {
        if(this.isMounted) {
            this.setState({this.data: res});
        }
    });
}

componentWillUnmount() {
    this.isMounted = false;
}

2 Comments

Read the article linked in my answer. isMounted is antpattern.
Woah, never seen that before. Thanks for the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.