Newer
Older
import { Table, Button, Alert } from "react-bootstrap";
constructor(props) {
super(props);
this.state = {
products: [],
update(row, key, value) {
this.setState({ error: null });
let products = this.state.products;
const code = products[row].code;
switch (key) {
case "code":
case "stock":
value = parseInt(value);
break;
case "price":
value = value * 100;
break;
}
products[row][key] = value;
this.setState({ products });
const body = JSON.stringify(products[row]);
headers: { "x-authentication": this.context.token },
method: "PUT",
body,
}).then((response) => {
if (!response.ok) {
this.setState({
error: response.status.toString() + " " + response.statusText,
});
}
});
}
delProduct(code) {
let products = this.state.products;
const index = products.findIndex((p) => p.code === code);
products.splice(index, 1);
this.setState({ products });
headers: { "x-authentication": this.context.token },
method: "DELETE",
}).then((response) => {
if (!response.ok) {
this.setState({
error: response.status.toString() + " " + response.statusText,
});
}
});
}
addProduct(product) {
let products = this.state.products;
products.push(product);
this.setState({ products });
const body = JSON.stringify(product);
headers: { "x-authentication": this.context.token },
method: "POST",
body,
}).then((response) => {
if (!response.ok) {
this.setState({
error: response.status.toString() + " " + response.statusText,
});
}
});
}
let alert = null;
if (this.state.error !== null) {
alert = (
<Alert variant="danger">
Ha ocurrido un error enviando cambios: {this.state.error}
</Alert>
);
}
<EditableCell
onChange={(v) => this.update(row, "code", v)}
value={product.code}
/>
<EditableCell
onChange={(v) => this.update(row, "name", v)}
value={product.name}
/>
<EditableCell
onChange={(v) => this.update(row, "price", v)}
value={printMoney(product.price)}
/>
<EditableCell
onChange={(v) => this.update(row, "stock", v)}
value={product.stock}
{isAdmin && (
<td sm={1}>
<Button
variant="danger"
onClick={() => this.delProduct(product.code)}
>
-
</Button>
</td>
)}
return (
<Fetcher
url="/api/product"
onFetch={(products) => this.setState({ products })}
>
<thead>
<tr>
<th>codigo</th>
<th>Nombre</th>
<th>Precio</th>
<th>Existencias</th>
</tr>
</thead>
<tbody>{entries}</tbody>
</Table>
{isAdmin && (
<div>
<p>Añadir producto:</p>
<ProductAdder addProduct={(p) => this.addProduct(p)} />
</div>
)}