0
Good evening. I’m having doubts about such a life cycle method of React and I’m doing tests. One of them is to cancel a request fetch, however, I’m not getting it. The console log. appears, but the request cancellation does not work. In my application, when clicking the button, there is a change of components and a request occurs. Here is my code:
const abortController = new AbortController()
class App extends Component {
constructor(props) {
super(props);
this.state = {
load: true
};
}
toogle = () => {
const { load } = this.state;
this.setState({ load: !load });
};
render(){
const { load } = this.state
return(
<>
{
load?
<>
<h1>Principal</h1>
<button onClick={this.toogle}>Clique</button>
</>:
<Teste click={this.toogle}/>
}
</>
)
}
}
class Teste extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log("fui montado");
fetch('https://pokeapi.co/api/v2/evolution-chain/?limit=6&offset=0',{
signal: abortController.signal
}).then(res => res.json()).then(res => console.log(res))
}
componentWillUnmount() {
console.log("fui desmontado");
abortController.abort()
}
render(){
return(
<>
<h1>Requisição</h1>
<button onClick={this.props.click}>Clique</button>
</>
)
}
}
Does anyone have any idea what might be going on?
Thanks for your attention!
You may have to create that variable inside the component?
– novic
@Thalesmaia, I think the complexity you will introduce just to cancel the AJAX request is not worth it (in this type of request). Wouldn’t it be better if you just stopped the
setState
after the request if the component is unmounted?– Luiz Felipe
Yes, but I read an article on React’s own website that says it’s considered anti-Pattern. And also in the documentation itself it says that one should cancel the request in Componentwillunmount, or is not a rule for all cases?
– Thales Maia