I have made a shopping cart in react. I have assigned a value to each button. The value shows in the dom so I know it's there.
I created a function to capture the value and then push it into an array. However, when I hit add to cart it say's "nothing added". I've been trying to find a way to listen for the value in the event listener but nothing seems to work.
I have tried putting just e.target.value but the outcome is the same.
Any ideas?
const [item, setItem] = useState([]);
function addCart(e) {
if (e.target.value === "") {
item.push(e.target.value);
console.log(item);
setCart(cart + 1);
} else {
console.log("nothing added");
}
}
<button
value={pro.price}
onClick={addCart}
className="bg-blue-500 text-white font-bold border-white p-2 rounded-md"
>
{"add to cart"}
</button>
I think you need to negate the condition in the if block. e.target.value !== ""
If you want to update your state item, you've to use setItem.
function addCart(e) {
if (e.target.value !== "") {
setItem([...item, e.target.value]);
console.log(item);
setCart(cart + 1);
} else {
console.log("nothing added");
}
}
I suggest that you could change your approach and use a class instead of a function as such :
class AddCard extends React.Component {
constructor(props) {
super(props)
this.state = {
value: 'VALUE'
}
}
handleChange (e) {
console.log('handleChange called')
}
handleClick () {
this.setState({value: 'UPDATED_VALUE'})
var event = new Event('input', { bubbles: true });
this.myinput.dispatchEvent(event);
}
render () {
return (
<div>
<input readOnly value={this.state.value} onChange={(e) => {this.handleChange(e)}} ref={(input)=> this.myinput = input}/>
<button onClick={this.handleClick.bind(this)}>Change Input</button>
</div>
)
}
}
ReactDOM.render(<AddCard />, document.getElementById('app'))
By doing so you'll be able to dissociate the click event and the change event