({ item, updateItem, fetchItems })
| 21 | } |
| 22 | |
| 23 | const Item: React.FC<ItemProps> = ({ item, updateItem, fetchItems }) => { |
| 24 | const app = React.useContext(AppContext); |
| 25 | const firstRender = React.useRef(true); |
| 26 | const [copy, setCopy] = React.useState<ItemType>(item); |
| 27 | const [catId, setCatId] = React.useState<number | string>(item.categoryId); |
| 28 | const [wUnit, setWUnit] = React.useState<any>(item.weight_unit); |
| 29 | const [editVisible, setEditVisible] = React.useState<boolean>(false); |
| 30 | |
| 31 | React.useEffect(() => { |
| 32 | if (!firstRender.current) { |
| 33 | handleSave(); |
| 34 | } |
| 35 | firstRender.current = false; |
| 36 | }, [catId, wUnit]); |
| 37 | |
| 38 | function update(key: string, value: any) { |
| 39 | const i = Object.assign({}, { ...copy, [key]: value }); |
| 40 | setCopy(i); |
| 41 | } |
| 42 | |
| 43 | function handleSave() { |
| 44 | if (!copy.name || isEqual(copy, item)) return; |
| 45 | const newCategory = !app.categories.map(c => c.id).includes(copy.categoryId); |
| 46 | updateItem({ ...copy, newCategory }) |
| 47 | .then(newItem => { |
| 48 | setCopy(newItem); |
| 49 | alertSuccess({ message: 'Item Updated.', duration: 2 }); |
| 50 | if (newCategory) { |
| 51 | app.fetchUser(); |
| 52 | } |
| 53 | }) |
| 54 | .catch(() => alertWarn({ message: 'Error updating item.' })); |
| 55 | } |
| 56 | |
| 57 | const categoryValue = categorySelectValue(app.categories, copy.categoryId); |
| 58 | const { product_name, name, weight_unit, weight } = copy; |
| 59 | return ( |
| 60 | <> |
| 61 | <Grid> |
| 62 | <div> |
| 63 | <Input value={name || ''} |
| 64 | onChange={v => update('name', v)} |
| 65 | onBlur={handleSave} |
| 66 | style={inlineStyles}/> |
| 67 | </div> |
| 68 | <div> |
| 69 | <Input value={product_name || ''} |
| 70 | placeholder="product name" |
| 71 | onChange={v => update('product_name', v)} |
| 72 | onBlur={handleSave} |
| 73 | style={inlineStyles}/> |
| 74 | </div> |
| 75 | <div> |
| 76 | <SelectCreatable |
| 77 | options={categoryOptions(app.categories)} |
| 78 | value={categoryValue} |
| 79 | onChange={(option: Option) => { |
| 80 | update('categoryId', option.value); |
nothing calls this directly
no test coverage detected