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

Create input to allow users to name their list #31

Merged
merged 5 commits into from
May 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 21 additions & 10 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ export function App() {
**/
const [timeOutErrorMsg, setTimeOutErrorMsg] = useState('');
const [joinListErrorMsg, setJoinListErrorMsg] = useState('');

const docExists = async (token) => {
return collection(db, `${token}`);
};
/**
* Callback function gets passed as a prop through Home component to retrieve generated token.
* The addDoc function call is wrapped in a Promise.race() method with a Promise that rejects after a certain timeout period.
Expand All @@ -35,16 +39,23 @@ export function App() {
**/
const setList = async (token) => {
try {
const result = await Promise.race([
addDoc(collection(db, `${token}`), {}),
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Promise timed out: Database not responding'));
}, 5000);
}),
]);
setListToken(token);
console.log('New list created with ID: ', result.id);
// Check if token already exists in the database
const tokenExists = await docExists(token);
if (tokenExists) {
console.log('Token already exists in the database.');
setListToken(token);
} else {
const result = await Promise.race([
addDoc(collection(db, `${token}`), {}),
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Promise timed out: Database not responding'));
}, 5000);
}),
]);
setListToken(token);
console.log('New list created with ID: ', result.id);
}
} catch (e) {
console.error('Error adding new list token: ', e);
setTimeOutErrorMsg('New List Error. Please refresh or try again later.');
Expand Down
4 changes: 2 additions & 2 deletions src/components/ListItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ export function ListItem({ item, listId }) {
return (
<li className="ListItem">
<div className="grid grid-cols-10 mb-3 items-center">
<li className="col-span-1 legendIcon">
<span className="col-span-1 legendIcon">
{purchaseUrgencyMessage(item)}
</li>
</span>
<label className="col-span-7" htmlFor={item.id}>
{item.name} {deleteError}
</label>
Expand Down
45 changes: 29 additions & 16 deletions src/views/Home.jsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { useState } from 'react';
import { generateToken } from '@the-collab-lab/shopping-list-utils';
// import { generateToken } from '@the-collab-lab/shopping-list-utils';
import './Home.css';

export function Home({ makeNewList, joinList, handleError, joinListErrorMsg }) {
const [inputValue, setInputValue] = useState('');
const [listName, setListName] = useState('');

const handleClick = () => {
const newToken = generateToken();
const handleClick = (event) => {
event.preventDefault();
const newToken = listName.trim().toLowerCase();
makeNewList(newToken);
};
/**
Expand All @@ -21,21 +23,32 @@ export function Home({ makeNewList, joinList, handleError, joinListErrorMsg }) {
return (
<div className="Home">
<p className="h3 pt-10">
Hello from the home (<code>/</code>) page!
To create a new shopping list, give your list a name.
</p>
{handleError ? <span>{handleError}</span> : null}
<button className="btn mt-4 mb-4" onClick={handleClick}>
Create a new list!
</button>
<form onSubmit={handleClick}>
<label className="text-2xl font-medium" htmlFor="listName">List name </label>
<input
type="text"
name="listName"
id="listName"
className="inputField"
required
value={listName}
onChange={(e) => setListName(e.target.value)}
pattern="[a-zA-Z0-9\s]+"
/>
<button className="btn mt-4 mb-4" type="submit">Create a new list!</button>
</form>
<div className="p-6 text-4xl text-center">-OR-</div>
<div className="JoinListForm">
<p className="text-2xl">
Join an existing shopping list by entering a three word token.
Join an existing shopping list by entering a list name.
</p>
{joinListErrorMsg ? <span>{joinListErrorMsg}</span> : null}
<form onSubmit={handleJoinList}>
<label className="text-2xl font-medium" htmlFor="input">
Share token:
Share list name:
</label>
<input
name="input"
Expand All @@ -44,14 +57,14 @@ export function Home({ makeNewList, joinList, handleError, joinListErrorMsg }) {
type="text"
value={inputValue}
onChange={(event) => setInputValue(event.target.value)}
pattern="[a-zA-Z]+ [a-zA-Z]+ [a-zA-Z]+"
onInvalid={(e) =>
e.target.setCustomValidity(
'Please enter 3 words with single space only.',
)
}
onInput={(e) => e.target.setCustomValidity('')}
pattern="[a-zA-Z0-9\s]+"
required
// onInvalid={(e) =>
// e.target.setCustomValidity(
// 'Please enter a valid list name i.e no numbers.',
// )
// }
// onInput={(e) => e.target.setCustomValidity('')}
/>
<button className="btn" type="submit">
Join an existing list
Expand Down
34 changes: 26 additions & 8 deletions src/views/List.jsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,48 @@
import { ListItem } from '../components';
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

import { comparePurchaseUrgency } from '../utils/items';
import Chippy3 from '/img/Chippy3.gif';
import './List.css';

export function List({ data, listId }) {
// creates a state variable to track searchbar input
const [query, setQuery] = useState('');
const [listName, setListName] = useState('');

// sets the state to the searchbar input as the user types
const handleSearch = (e) => {
setQuery(e.target.value);
};

// clears the searchbar and resets the filtered list to the whole list
const clearFilter = (e) => {
setQuery('');
};

const navigate = useNavigate();

const removeListFromStorage = () => {
//remove list from local storage
localStorage.removeItem('tcl-shopping-list-token');
// refresh page to force redirect to home page
window.location.reload();
};

useEffect(() => {
if (!listId) {
navigate('/');
}
const listName = localStorage.getItem('tcl-shopping-list-token');
setListName(listName);
}, [listName, listId, navigate]);

return (
<>
{/* <p>Welcome to your shopping list!</p> */}
<div id="chippyBox" className="grid grid-cols-3 pt-6">
<div className="chippy-suggestion chippy-suggestion-bottom-right col-span-2">
{data.length < 2
? 'Uh oh! Your shopping list is empty! Try using the "Add Item" button to begin your list!'
: 'Yummy! That list is looking good! Did you know that you can use the filter to search within your list?'}{' '}
{data.length < 1
? `Uh oh! ${listName} list is empty! Try using the "Add Item" button to begin your list!`
: `Yummy! That list is looking good! Did you know that you can use the filter to search within ${listName}?`}
</div>
<img
id="chippy"
Expand Down Expand Up @@ -79,6 +93,10 @@ export function List({ data, listId }) {
})}
</ul>
</div>
<>
<span>Want to check out a different list? </span>
<button className="btn mb-2" onClick={removeListFromStorage}>Click here</button>
</>
<div id="legend">
<h3 className="h3 pt-2 pb-3">Purchase Again?</h3>
<div className="grid grid-rows-2 gap-6">
Expand Down Expand Up @@ -110,4 +128,4 @@ export function List({ data, listId }) {
</div>
</>
);
}
}