0

how could I cancel fetch operation when component go away (unmount)

example : user open this screen and go back before fetch complete

here is what I have done

export default class LecturesScreen extends React.Component
{
      constructor(props){
        super(props);
        this.state = {lectures : [] , loadingNow : true}
    }

    componentDidMount(){
        this.loadLectures();
    }

    loadLectures = () =>{
        fetch(Link.api.lecture.newest , {method : 'POST'})
            .then((response) =>
            {
                this.setState({lectures : response , loadingNow: false});
            })
            .catch((error)=>
            {
                console.log(error);
            });
    };

    render(){
        return (
            <View>

                <List dataArray={this.state.lectures}
                      renderRow={(item) => <LectureListItem title={item.Title}/>}
                />

            </View>
        );
    }
}
Ali Faris
  • 17,754
  • 10
  • 45
  • 70

1 Answers1

2

Edit:

I don't think it's currently possible to cancel/abort a fetch request. You can follow the discussion here:

https://github.com/whatwg/fetch/issues/447

Call a function on componentDidUnmount like mentioned below.

componentWillUnmount(){
    this.unLoadLectures();
}

unLoadLectures = () =>{
   this.state = {lectures : [] , loadingNow : true}
};
Etherealm
  • 2,234
  • 3
  • 18
  • 34