Skip to content

Commit

Permalink
Merge pull request #27 from the-collab-lab/mp-sm-check-for-existing-a…
Browse files Browse the repository at this point in the history
…nd-empty-items

Added check for similar items using regex.
  • Loading branch information
sar-mko authored Sep 17, 2024
2 parents ee33a0d + 9edd71e commit 2907fc7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
5 changes: 4 additions & 1 deletion src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,10 @@ export function App() {
element={<Home data={lists} setListPath={setListPath} />}
/>
<Route path="/list" element={<List data={data} userId={userId} />} />
<Route path="/manage-list" element={<ManageList userId={userId} />} />
<Route
path="/manage-list"
element={<ManageList userId={userId} list={data} />}
/>
</Route>
</Routes>
</Router>
Expand Down
34 changes: 31 additions & 3 deletions src/views/ManageList.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useState } from 'react';
import { addItem, shareList } from '../api';

export function ManageList({ userId }) {
export function ManageList({ userId, list }) {
const [formData, setFormData] = useState({
name: '',
frequency: '',
Expand All @@ -15,7 +15,6 @@ export function ManageList({ userId }) {
[e.target.name]: e.target.value,
}));
}

function handleEmailChange(e) {
e.preventDefault();
setEmail(e.target.value);
Expand All @@ -31,10 +30,39 @@ export function ManageList({ userId }) {
const listPath = localStorage.getItem('tcl-shopping-list-path');

if (!listPath) {
window.alert('List is not existed.');
window.alert('List does not exist.');
return;
}

const formDataCheck = formData.name
.replace(/[^A-Z0-9]/gi, '')
.toLowerCase();

if (
list.find(
(item) =>
item.name.trim().toLowerCase() === formData.name.trim().toLowerCase(),
)
) {
window.alert(`${formData.name} already exists in your list.`);
return;
}

if (
list.some((item) => {
const itemCheck = item.name.replace(/[^A-Z0-9]/gi, '').toLowerCase();
return itemCheck === formDataCheck || formDataCheck.includes(itemCheck);
})
) {
if (
!window.confirm(
`A similar item is already on your list. Do you still want to add ${formData.name}?`,
)
) {
return;
}
}

addItem(listPath, {
itemName: formData.name,
daysUntilNextPurchase: parseInt(formData.frequency),
Expand Down

0 comments on commit 2907fc7

Please sign in to comment.