Hello i've been trying to implement componentDidUpdate. But i have a problem. But i think im doing some part correct, like i have the If statement required? im pretty sure this worked like 2 hours ago but now it's looping in the console. what am i missing?
I will start by posting the most relevant info from my component. I also have CRUD in my component. The view is updating fine after every change but with a downside of a loop from componentDidUpdate that wont stop.
i Would appreciate some help on this matter i've tried to do some research, i guess i should not call the API again? but how can i fix this issue.
i will only post the relevant code from my component.
enter code here
state = { productList: [], statusMsg: "", };
// READ FROM API
getDataFromProductsApi() {
axios
.get("https://localhost:44366/api/Products/")
.then((res) => {
console.log(res.data);
this.setState({
productList: res.data,
});
})
.catch((error) => {
console.log(error);
this.setState({ statusMsg: "Error retreiving data" });
if (axios.isCancel(error)) return;
});
}
componentDidMount() {
this.getDataFromProductsApi();
}
// reupdate the state on Changes
componentDidUpdate(prevProps, prevState) {
console.warn("changes");
if (prevState.productList !== this.state.productList) {
axios.get("https://localhost:44366/api/Products/").then((res) => {
console.log(res.data);
this.setState({
productList: res.data,
});
});
}
}
//Post axios .post("https://localhost:44366/api/Products/", this.state) .then((response) => { console.log(response); this.setState({ statusMessage: "Product Added" }); }) .catch((error) => { console.log(error); this.setState({ statusMessage: "Something went wrong" }); if (axios.isCancel(error)) return; }); };
// DELETE FROM API
deleteProduct = (productId, productName) => {
if (window.confirm("Are you sure? you want to delete")) {
axios
.delete(`https://localhost:44366/api/Products/${productId}`)
.then((response) => {
console.log(response);
this.setState({
statusMsg: `Product name: ${productName} With the ID: ${productId} was removed!`,
//updating state to show the changes in view instantly
// productList: this.state.productList.filter(
// (item) => item.id !== productId
//),
});
});
}
};
prevState.productList !== this.state.productList
will alwaysreturn true
because they are arrays – TheLastStarkJSON.stringify(prevState.productList) == JSON.stringify(this.state.productList)
. Or lodash equality functions will also be great. – TheLastStarkif(JSON.stringify(prevState.productList) == JSON.stringify(this.state.productList))
It should be inside theif()
– TheLastStark