Skip to content

Commit a799af8

Browse files
Merge pull request #44 from the-collab-lab/wc-gb-empty-duplicate-item-alert
[Issue 10]: Empty/duplicate item alerts
2 parents e73e0e6 + b2adf32 commit a799af8

File tree

3 files changed

+31
-6
lines changed

3 files changed

+31
-6
lines changed

src/components/AddItems.jsx

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { useCallback } from 'react';
2-
import { useStateWithStorage } from '../utils';
2+
import { useStateWithStorage, normalizeItemName } from '../utils';
33
import { addItem } from '../api';
44
import TextInputElement from './TextInputElement';
55
import RadioInputElement from './RadioInputElement';
@@ -40,6 +40,22 @@ export function AddItems({ items }) {
4040
event.target.elements['purchase-date'].value;
4141

4242
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+
}
4359
await addItem(listPath, {
4460
itemName,
4561
daysUntilNextPurchase,
@@ -63,10 +79,13 @@ export function AddItems({ items }) {
6379
type="text"
6480
id="item-name"
6581
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>
7089
{Object.entries(daysUntilPurchaseOptions).map(([key, value]) => (
7190
<RadioInputElement
7291
key={key}
@@ -76,7 +95,6 @@ export function AddItems({ items }) {
7695
required={true}
7796
/>
7897
))}
79-
8098
<button type="submit">Submit</button>
8199
</form>
82100
</div>

src/utils/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export * from './dates';
22
export * from './hooks';
3+
export * from './normalize';

src/utils/normalize.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export function normalizeItemName(itemName) {
2+
return itemName
3+
.trim()
4+
.toLowerCase()
5+
.replace(/[&\/\\#, +$!,~%.'":*?<>{}]/g, '');
6+
}

0 commit comments

Comments
 (0)