Reputation: 169
I've been beating my head against the desk today. Instead of dealing with forms/APIs, I'm trying to let people make an order (with a shopping cart) directly via email using a mailto link. My data looks like this:
[
{
"image": "https://static.wixstatic.com/awefawef.jpg",
"name": "xyz",
"price": "20.00",
"id": "3",
"quantity": 30
},
{
"image": "https://static.wixstatic.com/media/aweawfefeaw.png",
"name": "abc",
"price": "20.00",
"id": "4",
"quantity": 20
}
]
Trying to have the email be either a table with the the name, price, and quantity or just some sort of simple list/invoice like:
Items Needed:
- name: abc
quantity:30
price: $600
- name: xyz
quantity: 20
price: $400
- Total Price: $1000
customer name: [insert name]
customer email: [insert email]
customer company: [insert company]
I'm struggling to parse the data in some sort of usable form for the body
in the mailto link. Here's what I've got so far (this is in React)...the shopping cart array is this.state.cart
:
sendEmail(){
let body;
this.state.cart.forEach(function(element) {
//console.log(element);
body = 'name:' + element.name;
body += '\nprice:' + element.price;
body += '\nquanity:' + element.quantity;
body += '\ntotal:' + element.quantity * element.price;
});
window.location.href="mailto:[email protected]?subject= Order for [Insert Name]&body=" + encodeURIComponent(body)
}
This sort of works but I can't figure out how to get all of them in an ordered fashion. Only the last one works. It also opens in the native Mac mail app. As you can tell, I'm a bit turned around.
Upvotes: 2
Views: 2565
Reputation: 30370
Does this achieve the desired result?
function sendEmail() {
// Format a string itemising cart by mapping elements to sub-strings and joining the result
const items = this.state.cart.map(function(element) {
return `
- name ${ element.name }
price: $${ element.price.toFixed(2) }
quantity: ${ element.quantity }
total: ${ (element.quantity * element.price).toFixed(2) }
`;
}).join('\n');
// Calculate total price via reduction, and format to a number to 2dp
const totalPrice = this.state.cart.reduce(function(sum, element) {
return sum + (element.quantity * element.price);
}, 0.0).toFixed(2);
// Format body string with itemised cart, total price, etc
const body = `
${ items }
Total Price: $${totalPrice}
customer name: [insert name]
customer email: [insert email]
customer company: [insert company]
`;
window.location.href = 'mailto:[email protected]?subject=Order for [Insert Name]&body=' + encodeURIComponent(body);
}
Upvotes: 2