I’m trying to learn react so I’m rebuilding the magento2 minicart in react, all seems to be working well apart from I’m having issues submitting the form data if the quantity changes - I’m trying to do this like so:
onChange = (e) => {
this.setState({ qty: e.target.value }, () => {
axios({
headers: {
'Content-Type': 'application/json'
},
method: 'post',
url: '/checkout/sidebar/updateItemQty/',
data: {
item_id: 13,
item_qty: this.state.qty,
form_key: 'KTC30XGNGahjfVmn'
}
});
});
}
On a refresh of the page the basket quantity doesn’t update, when checking how default mangento2 posts the information it seems to be different as you can see on the images - how can I change my code above so it matches the default post if that’s the issue?
Update: changing params to data makes the request 302 and changes the type to HTML and can't seem to get it back to json
params
is to send data in query parameter. To send data in post body
use body
option. Like this:
Edit
Since you are submitting form data, you need to specify content type as application/x-www-form-urlencoded
and also need to change way how we send data.
axios({
method: 'post',
url: '/checkout/sidebar/updateItemQty/',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: queryString.stringify({
item_id: 9,
item_qty: this.state.qty,
form_key: 'KTC30XGNGahjfVmn'
})
});
});
You can get query string module using from here https://github.com/Gozala/querystring#readme
It was probably an M2 specific solution but it needed to be built up as a form like below so it submits it as form data:
let addToCartForm = new FormData();
addToCartForm.set('item_id', this.props.item_id);
addToCartForm.set('item_qty', this.state.qty);
addToCartForm.set('form_key', document.getElementsByName('form_key')[0].value);
axios({
url: '/checkout/sidebar/updateItemQty/',
method: 'post',
data: addToCartForm
}).then(() => {
window.updateCartData();
});