Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Toast Notification #69

Merged
merged 10 commits into from
Oct 15, 2024
Merged
23 changes: 22 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"firebase": "^10.12.5",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.0"
"react-router-dom": "^6.26.0",
"react-toastify": "^10.0.5"
},
"devDependencies": {
"@nabla/vite-plugin-eslint": "^2.0.4",
Expand Down
12 changes: 12 additions & 0 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { Home, Layout, List, ManageList } from './views';
import { useAuth, useShoppingListData, useShoppingLists } from './api';

import { useStateWithStorage } from './utils';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

export function App() {
/**
Expand Down Expand Up @@ -42,6 +44,16 @@ export function App() {

return (
<Router>
<ToastContainer
position="top-center"
autoClose={4000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
draggable
pauseOnHover
theme="dark"
/>
<Routes>
<Route path="/" element={<Layout />}>
<Route
Expand Down
11 changes: 7 additions & 4 deletions src/components/AddItems.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useStateWithStorage, normalizeItemName } from '../utils';
import { addItem } from '../api';
import TextInputElement from './TextInputElement';
import RadioInputElement from './RadioInputElement';
import { toast } from 'react-toastify';

const daysUntilPurchaseOptions = {
Soon: 7,
Expand All @@ -24,7 +25,7 @@ export function AddItems({ items }) {

try {
if (itemName.trim() === '') {
alert('Please add an item name.');
toast.error('Please add an item name.');
return;
}
// normalize the name by removing all punctuation and spaces to check if the normalized item is already in the list
Expand All @@ -35,19 +36,21 @@ export function AddItems({ items }) {
normalizeItemName(item.name),
);
if (currentItems.includes(normalizedItemName)) {
alert('This item already exists in the list');
toast.error('This item already exists in the list');
return;
}
}
await addItem(listPath, {
itemName,
daysUntilNextPurchase,
});
alert(
toast.success(
`${itemName} was added to the list! The next purchase date is set to ${daysUntilNextPurchase} days from now.`,
);
} catch (error) {
alert(`Item was not added to the database, Error: ${error.message}`);
toast.error(
`Item was not added to the database, Error: ${error.message}`,
);
} finally {
event.target.reset();
}
Expand Down
5 changes: 3 additions & 2 deletions src/components/ListItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useState } from 'react';
import './ListItem.css';
import { updateItem, deleteItem } from '../api';
import { calculateDateNextPurchased, ONE_DAY_IN_MILLISECONDS } from '../utils';
import { toast } from 'react-toastify';

const currentDate = new Date();

Expand Down Expand Up @@ -39,7 +40,7 @@ export function ListItem({ item, listPath }) {

await updateItem(listPath, id, { ...updatedItem });
} catch (error) {
alert(`Item was not marked as purchased`, error.message);
toast.error(`Item was not marked as purchased`, error.message);
}
}
};
Expand All @@ -49,7 +50,7 @@ export function ListItem({ item, listPath }) {
try {
await deleteItem(listPath, id);
} catch (error) {
alert('Item was not deleted');
toast.error('Item was not deleted');
}
}
return;
Expand Down
9 changes: 5 additions & 4 deletions src/components/ShareList.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { shareList, useAuth } from '../api';
import { useStateWithStorage } from '../utils';
import TextInputElement from './TextInputElement';
import { toast } from 'react-toastify';

export function ShareList() {
const [listPath] = useStateWithStorage('tcl-shopping-list-path', null);
Expand All @@ -13,11 +14,11 @@ export function ShareList() {
const listShared = await shareList(listPath, userId, emailData);

if (listShared === '!owner') {
alert('You cannot share the list you do not own.');
toast.error('You cannot share the list you do not own.');
} else if (listShared === 'shared') {
alert('List was shared with recipient.');
toast.success('List was shared with recipient.');
} else {
alert(
toast.error(
"The list was not shared because the recipient's email address does not exist in the system.",
);
}
Expand All @@ -29,7 +30,7 @@ export function ShareList() {
const emailData = event.target['email-input'].value;

if (userEmail === emailData) {
alert('You cannot share the list with yourself.');
toast.error('You cannot share the list with yourself.');
} else {
shareCurrentList(emailData);
}
Expand Down
3 changes: 2 additions & 1 deletion src/hooks/useEnsureListPath.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'react-toastify';

/*
* This custom hook ensures that a user has a list path in localStorage.
Expand All @@ -13,7 +14,7 @@ export function useEnsureListPath() {
useEffect(() => {
const listPath = localStorage.getItem('tcl-shopping-list-path');
if (!listPath) {
alert(
toast.error(
'It seems like you landed here without first creating a list or selecting an existing one. Please select or create a new list first. Redirecting to Home.',
);
navigate('/');
Expand Down
7 changes: 4 additions & 3 deletions src/views/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { SingleList } from '../components';
import { useNavigate } from 'react-router-dom';
import { createList } from '../api';
import TextInputElement from '../components/TextInputElement';
import { toast } from 'react-toastify';

export function Home({ data, setListPath, userId, userEmail }) {
const navigate = useNavigate();
Expand All @@ -16,17 +17,17 @@ export function Home({ data, setListPath, userId, userEmail }) {

try {
if (currentLists.includes(listName.toLowerCase())) {
alert('The list already exists. Please enter a different name.');
toast.error('The list already exists. Please enter a different name.');
return;
}

const listPath = await createList(userId, userEmail, listName);
setListPath(listPath);
alert('List added');
toast.success('List added');
navigate('/list');
} catch (err) {
console.error(err);
alert('List not created');
toast.error('List not created');
} finally {
event.target.reset();
}
Expand Down
32 changes: 0 additions & 32 deletions tests/List.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,6 @@
import { List } from '../src/views/List';
import { mockShoppingListData } from '../src/mocks/__fixtures__/shoppingListData';

beforeEach(() => {
Object.defineProperty(window, 'localStorage', {
value: {
getItem: vi.fn((key) => {
if (key === 'tcl-shopping-list-path') {
return '/groceries';
}
return null;
}),
setItem: vi.fn(),
clear: vi.fn(),
},
writable: true,
});

vi.spyOn(window, 'alert').mockImplementation(() => {});
});

describe('List Component', () => {
test('renders the shopping list name, search field, and all list items from the data prop', () => {
render(
Expand All @@ -29,7 +11,7 @@
</MemoryRouter>,
);

expect(screen.getByText('groceries')).toBeInTheDocument();

Check failure on line 14 in tests/List.test.jsx

View workflow job for this annotation

GitHub Actions / Run Tests

tests/List.test.jsx > List Component > renders the shopping list name, search field, and all list items from the data prop

TestingLibraryElementError: Unable to find an element with the text: groceries. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. Ignored nodes: comments, script, style <body> <div /> </body> ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:76:38 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ tests/List.test.jsx:14:17

Check failure on line 14 in tests/List.test.jsx

View workflow job for this annotation

GitHub Actions / Run Tests

tests/List.test.jsx > List Component > renders the shopping list name, search field, and all list items from the data prop

TestingLibraryElementError: Unable to find an element with the text: groceries. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. Ignored nodes: comments, script, style <body> <div /> </body> ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:76:38 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ tests/List.test.jsx:14:17
expect(screen.getByLabelText('Search Item:')).toBeInTheDocument();

mockShoppingListData.forEach((item) => {
Expand All @@ -44,25 +26,11 @@
</MemoryRouter>,
);

expect(screen.getByText('Welcome to groceries!')).toBeInTheDocument();

Check failure on line 29 in tests/List.test.jsx

View workflow job for this annotation

GitHub Actions / Run Tests

tests/List.test.jsx > List Component > shows welcome message and AddItems component when no items are present

TestingLibraryElementError: Unable to find an element with the text: Welcome to groceries!. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. Ignored nodes: comments, script, style <body> <div /> </body> ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:76:38 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ tests/List.test.jsx:29:17

Check failure on line 29 in tests/List.test.jsx

View workflow job for this annotation

GitHub Actions / Run Tests

tests/List.test.jsx > List Component > shows welcome message and AddItems component when no items are present

TestingLibraryElementError: Unable to find an element with the text: Welcome to groceries!. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. Ignored nodes: comments, script, style <body> <div /> </body> ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:76:38 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ tests/List.test.jsx:29:17
expect(screen.getByLabelText('Item Name:')).toBeInTheDocument();
expect(screen.getByLabelText('Soon')).toBeInTheDocument();
expect(screen.getByLabelText('Kind of soon')).toBeInTheDocument();
expect(screen.getByLabelText('Not soon')).toBeInTheDocument();
expect(screen.getByText('Submit')).toBeInTheDocument();
});

test('triggers alert and redirects when no list path is found in localStorage', () => {
window.localStorage.getItem.mockReturnValueOnce(null);

render(
<MemoryRouter>
<List data={[]} listPath={null} />
</MemoryRouter>,
);

expect(window.alert).toHaveBeenCalledWith(
'It seems like you landed here without first creating a list or selecting an existing one. Please select or create a new list first. Redirecting to Home.',
);
});
});
32 changes: 0 additions & 32 deletions tests/ManageList.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,6 @@
import { ManageList } from '../src/views/ManageList';
import { MemoryRouter } from 'react-router-dom';

beforeEach(() => {
Object.defineProperty(window, 'localStorage', {
value: {
getItem: vi.fn((key) => {
if (key === 'tcl-shopping-list-path') {
return '/groceries';
}
return null;
}),
setItem: vi.fn(),
clear: vi.fn(),
},
writable: true,
});

vi.spyOn(window, 'alert').mockImplementation(() => {});
});

describe('ManageList Component', () => {
test('renders AddItems component with submit button and radio buttons', () => {
render(
Expand All @@ -28,7 +10,7 @@
</MemoryRouter>,
);

expect(screen.getByLabelText('Item Name:')).toBeInTheDocument();

Check failure on line 13 in tests/ManageList.test.jsx

View workflow job for this annotation

GitHub Actions / Run Tests

tests/ManageList.test.jsx > ManageList Component > renders AddItems component with submit button and radio buttons

TestingLibraryElementError: Unable to find a label with the text of: Item Name: Ignored nodes: comments, script, style <body> <div /> </body> ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 ❯ getAllByLabelText node_modules/@testing-library/dom/dist/queries/label-text.js:111:38 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ tests/ManageList.test.jsx:13:17

Check failure on line 13 in tests/ManageList.test.jsx

View workflow job for this annotation

GitHub Actions / Run Tests

tests/ManageList.test.jsx > ManageList Component > renders AddItems component with submit button and radio buttons

TestingLibraryElementError: Unable to find a label with the text of: Item Name: Ignored nodes: comments, script, style <body> <div /> </body> ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 ❯ getAllByLabelText node_modules/@testing-library/dom/dist/queries/label-text.js:111:38 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ tests/ManageList.test.jsx:13:17
expect(screen.getByLabelText('Soon')).toBeInTheDocument();
expect(screen.getByLabelText('Kind of soon')).toBeInTheDocument();
expect(screen.getByLabelText('Not soon')).toBeInTheDocument();
Expand All @@ -42,21 +24,7 @@
</MemoryRouter>,
);

expect(screen.getByPlaceholderText('Enter email')).toBeInTheDocument();

Check failure on line 27 in tests/ManageList.test.jsx

View workflow job for this annotation

GitHub Actions / Run Tests

tests/ManageList.test.jsx > ManageList Component > renders ShareList component with email input and invite button

TestingLibraryElementError: Unable to find an element with the placeholder text of: Enter email Ignored nodes: comments, script, style <body> <div /> </body> ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:76:38 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ tests/ManageList.test.jsx:27:17

Check failure on line 27 in tests/ManageList.test.jsx

View workflow job for this annotation

GitHub Actions / Run Tests

tests/ManageList.test.jsx > ManageList Component > renders ShareList component with email input and invite button

TestingLibraryElementError: Unable to find an element with the placeholder text of: Enter email Ignored nodes: comments, script, style <body> <div /> </body> ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:76:38 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ tests/ManageList.test.jsx:27:17
expect(screen.getByText('Invite User')).toBeInTheDocument();
});

test('triggers alert and redirects when no list path is found in localStorage', () => {
window.localStorage.getItem.mockReturnValueOnce(null);

render(
<MemoryRouter>
<ManageList />
</MemoryRouter>,
);

expect(window.alert).toHaveBeenCalledWith(
'It seems like you landed here without first creating a list or selecting an existing one. Please select or create a new list first. Redirecting to Home.',
);
});
});
Loading