'How can I save React state on rerender?
I want to create a simple shop in react and I've run into a little problem. Every time I click the Element it changes to true (like intended), but when I resize the window everything resets back to false. I thought that class components save the variables and don't reset back like functional components.
How can I implement it, so that it saves the checked variable?
Second Question:
How would I be able to add an object of the class Item into a useState array?
My thought process:
- Click the Element you want to add to the shopping cart
- Set checked variable so I can display a checkbox on the Item
- Something like
setShoppingCart(shoppingCart =>(...shoppingCart,this))
where shoppingCart is a useState array - And then have a
useEffect(()=>{shoppingCart.map((e) => (<span>e.offerId<span/>))},shoppingCart])
Please Help me :)
class Item extends Component {
constructor(props) {
super(props)
this.name = props.name
this.preis = props.preis
this.dauer = props.dauer
this.offerId = props.offerId
this.state = {
checked: false
};
}
changeState() {
this.setState({checked : !this.state.checked})
console.log(this.state.checked)
}
render() {
return (
<>
<div onClick={() => this.changeState()} className={style.Item + ' m-2 p-3'}>
{this.name} {this.preis} {this.dauer} {this.offerId} {this.state.checked ? "true" : "false"}
</div>
</>
)
}
}
Edit:
Here is the whole code GitHub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|