Skip to content
Snippets Groups Projects
Commit 98d4eb2b authored by meskio's avatar meskio :tent:
Browse files

Edit products

parent 0edcd625
Branches
Tags
No related merge requests found
import React, { useState } from "react";
import { Form } from "react-bootstrap";
function EditableCell(props) {
const [data, setData] = useState(props.value);
const [editing, setEditing] = useState(false);
if (props.ro || !editing) {
return <td onClick={() => setEditing(true)}>{props.value}</td>;
}
const submit = (e) => {
e.preventDefault();
props.onChange(data);
setEditing(false);
};
return (
<td>
<Form onSubmit={submit}>
<Form.Control value={data} onChange={(e) => setData(e.target.value)} />
</Form>
</td>
);
}
export default EditableCell;
import React from "react";
import { Table } from "react-bootstrap";
import { Table, Alert } from "react-bootstrap";
import Fetcher from "./Fetcher";
import EditableCell from "./EditableCell";
import AuthContext from "./AuthContext";
import { printMoney } from "./util";
class ProductList extends React.Component {
static contextType = AuthContext;
constructor(props) {
super(props);
this.state = {
products: [],
error: null,
};
}
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]);
fetch("/api/product/" + code, {
headers: { "x-authentication": this.context.token },
method: "PUT",
body,
}).then((response) => {
if (!response.ok) {
this.setState({
error: response.status.toString() + " " + response.statusText,
});
}
});
}
render() {
const entries = this.state.products.map((product) => {
let alert = null;
if (this.state.error !== null) {
alert = (
<Alert variant="danger">
Ha ocurrido un error enviando cambios: {this.state.error}
</Alert>
);
}
const isAdmin = this.context.role !== "admin";
const entries = this.state.products.map((product, row) => {
return (
<tr key={product.code}>
<td>{product.code}</td>
<td>{product.name}</td>
<td>{printMoney(product.price)}</td>
<td>{product.stock}</td>
<EditableCell
onChange={(v) => this.update(row, "code", v)}
value={product.code}
ro={isAdmin}
/>
<EditableCell
onChange={(v) => this.update(row, "name", v)}
value={product.name}
ro={isAdmin}
/>
<EditableCell
onChange={(v) => this.update(row, "price", v)}
value={printMoney(product.price)}
ro={isAdmin}
/>
<EditableCell
onChange={(v) => this.update(row, "stock", v)}
value={product.stock}
ro={isAdmin}
/>
</tr>
);
});
......@@ -28,6 +92,7 @@ class ProductList extends React.Component {
url="/api/product"
onFetch={(products) => this.setState({ products })}
>
{alert}
<Table striped bordered hover>
<thead>
<tr>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment