I'm building a kind of e-commerce app. As we know, every e-commerce app has wish list feature. In my product list, there's a like button on the card item. When user click it, it calls an API to set isLiked property to true (boolean) and updated the database.
When user click that card item, it should navigate him to it's detail page, which also has like button. I call the detail API in componentDidMount... Here's the thing:
I should render the like button with red color if the property of isLiked from detail API is true. So, to do that, I set my state in constructor with the props value:
constructor(props) {
super(props);
this.state = {
isLikedForCompare: this.props.detailProduct.is_liked, // true
isLiked: this.props.detailProduct.is_liked, // true
selectedItem: ''
};
}
I add isLikedForCompare for comparing because we can't access this in getDerivedStateFromProps.
static getDerivedStateFromProps(nextProps, prevState) {
let defaultItem = ''
// some code to get default item
const { is_liked: isLiked } = nextProps.detailProduct;
let selected = {};
if (prevState.selectedItem === '') {
selected = {
selectedItem: defaultItem,
};
}
return {
...selected,
isLiked: prevState.isLikedForCompare !== isLiked ? isLiked : prevState.isLikedForCompare
};
}
I have that block of code about selectedItem which always satisfy the condition because the initial value is always empty. This code is works for other feature , so I need to let them alone, that's why my code is like this. So, move on... Now I can get the value of isLiked from props. The like button in my view is red now. But the problem is when I click that button. My expectation is when I click that button, the button change to white because I just change my state using this.setState but why getDerivedStateFromProps is called after setState?
This is a problem because:
isLiked: prevState.isLikedForCompare !== isLiked ? isLiked : prevState.isLikedForCompare will always false. So my state isLike will always true!
How to fix this?