Newer
Older
import React from 'react';
import { Redirect } from 'react-router-dom';
import { Container, Row, Col, Button, Alert, Spinner } from 'react-bootstrap';
import ProductPicker from '../ProductPicker';
class Purchase extends React.Component {
static contextType = AuthContext;
constructor(props) {
super(props);
this.state = {
purchase: [],
total: 0,
const add = (acc, p) => acc + (p.price*p.ammount);
const total = purchase.reduce(add, 0);
}
send() {
this.setState({isLoading: true, error: null, noMoney: false});
const body = JSON.stringify(this.state.purchase.map(p => {
return {
};
}));
fetch("/api/purchase", {headers: {'x-authentication': this.context.token}, method: "POST", body})
.then(response => {
if (response.status === 400) {
var error = new Error("Not enough money");
error.name ="not-money";
throw error;
} else if (!response.ok) {
throw new Error(response.status.toString()+' '+response.statusText);
}
return response.json();
})
.then(p => {
this.setState({transactionId: p.ID, isLoading: false});
}
});
}
render() {
if (this.state.isLoading) {
return <Spinner animation="border" />;
}
let alert;
alert = (
<Alert variant="warning">
No tienes suficiente dinero para realizar esta compra.
</Alert>
);
} else if (this.state.error != null) {
alert = (
<Alert variant="danger">
Ha ocurrido un error enviando la compra: {this.state.error}
</Alert>
);
}
if (this.state.transactionId !== null) {
return <Redirect to={"/transaction/"+this.state.transactionId} />;
<ProductPicker ammount
picks={this.state.purchase}
setPicks={purchase => this.setPurchase(purchase)}
/>
<br />
<Row>
<Col>
<h3>Total: {printMoney(this.state.total)}€</h3>
</Col>
<Col>
<div className="text-right">
<Button onClick={() => this.send()}>Finalizar compra</Button>