1
1
import { useCallback } from 'react' ;
2
- import { useStateWithStorage } from '../utils' ;
2
+ import { useStateWithStorage , normalizeItemName } from '../utils' ;
3
3
import { addItem } from '../api' ;
4
4
import TextInputElement from './TextInputElement' ;
5
5
import RadioInputElement from './RadioInputElement' ;
@@ -40,6 +40,22 @@ export function AddItems({ items }) {
40
40
event . target . elements [ 'purchase-date' ] . value ;
41
41
42
42
try {
43
+ if ( itemName . trim ( ) === '' ) {
44
+ alert ( 'Please add an item name.' ) ;
45
+ return ;
46
+ }
47
+ // normalize the name by removing all punctuation and spaces to check if the normalized item is already in the list
48
+ const normalizedItemName = normalizeItemName ( itemName ) ;
49
+ if ( items ) {
50
+ // normalize the existing list items to compare them to the new input
51
+ const currentItems = items . map ( ( item ) =>
52
+ normalizeItemName ( item . name ) ,
53
+ ) ;
54
+ if ( currentItems . includes ( normalizedItemName ) ) {
55
+ alert ( 'This item already exists in the list' ) ;
56
+ return ;
57
+ }
58
+ }
43
59
await addItem ( listPath , {
44
60
itemName,
45
61
daysUntilNextPurchase,
@@ -63,10 +79,13 @@ export function AddItems({ items }) {
63
79
type = "text"
64
80
id = "item-name"
65
81
placeholder = "Enter item name"
66
- label = "Item Name:"
67
- required = { true }
68
- />
69
-
82
+ pattern = "^[^\s].+[^\s]$"
83
+ >
84
+ Item Name:
85
+ </ TextInputElement >
86
+ < label htmlFor = "item-name" required = { true } >
87
+ Item Name:
88
+ </ label >
70
89
{ Object . entries ( daysUntilPurchaseOptions ) . map ( ( [ key , value ] ) => (
71
90
< RadioInputElement
72
91
key = { key }
@@ -76,7 +95,6 @@ export function AddItems({ items }) {
76
95
required = { true }
77
96
/>
78
97
) ) }
79
-
80
98
< button type = "submit" > Submit</ button >
81
99
</ form >
82
100
</ div >
0 commit comments