Reputation: 395
I am getting data with API using React. But when I redirect, I get an error, can you help? Thank you so much.
Very thanks
componentDidMount() {
fetch(`${this.domain}/api/debt/list?customer=` + this.props.customerInfo.customer.ID, {
headers: {
Authorization: `Bearer ${localStorage.getItem('id_token')}`,
"Content-Type": "application/json",
}
})
.then(res => {
if (res.ok) {
return res.json();
} else {
return res.json().then(err => Promise.reject(err));
}
})
.then(json => {
this.setState({
items: json
});
// console.log(json)
})
.catch(error => {
//console.log('request failed:', error);
return error;
});
}
render() {
const { isLoaded, items } = this.state;
if (this.props.customerInfo.customer.ID === "-1") {
return <Redirect to={"/customerlist"}/>
}
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method. in AuthWrapped (created by ConnectFunction) in ConnectFunction (at DefaultLayout.js:73) in Route (at DefaultLayout.js:68)
Upvotes: 1
Views: 84
Reputation: 2452
I believe this happens when you have this.props.customerInfo.customer.ID === "-1"
true. In this case, you are redirecting, but the API call you made is still pending and upon it's completion you are using setState
on a component which does not exist since you already redirected.
1) Easiest way to fix this is before using setState
put a conditional check for the case in which you have redirected or better you have a separate flag to check this.
constructor(){
this.isComponentDestroyed = false;
}
componentDidMount(){
fetch(...)
.then(()=>{
if(!this.isComponentDestroyed){
this.setState({
items: json
});
}
})
}
componentWillUnmount(){
this.isComponentDestroyed = true;
}
2) You can also check on how to cancel the fetch
call. Ref How do I cancel an HTTP fetch() request?
From the comments, adding a reference to How to cancel a fetch on componentWillUnmount
Upvotes: 1