diff --git a/src/api/firebase.js b/src/api/firebase.js index de46f9c..8b3b627 100644 --- a/src/api/firebase.js +++ b/src/api/firebase.js @@ -139,7 +139,7 @@ export async function createList(userId, userEmail, listName) { export async function shareList(listPath, currentUserId, recipientEmail) { // Check if current user is owner. if (!listPath.includes(currentUserId)) { - return; + return '!owner'; } // Get the document for the recipient user. const usersCollectionRef = collection(db, 'users'); @@ -151,9 +151,14 @@ export async function shareList(listPath, currentUserId, recipientEmail) { // Add the list to the recipient user's sharedLists array. const listDocumentRef = doc(db, listPath); const userDocumentRef = doc(db, 'users', recipientEmail); - updateDoc(userDocumentRef, { - sharedLists: arrayUnion(listDocumentRef), - }); + try { + updateDoc(userDocumentRef, { + sharedLists: arrayUnion(listDocumentRef), + }); + return 'shared'; + } catch { + return; + } } /** diff --git a/src/views/ManageList.jsx b/src/views/ManageList.jsx index f10946d..ec7586f 100644 --- a/src/views/ManageList.jsx +++ b/src/views/ManageList.jsx @@ -1,6 +1,6 @@ import { useCallback, useState } from 'react'; import { useStateWithStorage } from '../utils'; -import { addItem } from '../api'; +import { addItem, shareList, useAuth } from '../api'; const soonDate = 7; const kindOfSoonDate = 14; @@ -9,16 +9,21 @@ const notSoonDate = 30; export function ManageList() { const [daysUntilNextPurchase, setDaysUntilNextPurchase] = useState(null); const [itemName, setItemName] = useState(''); + const [emailData, setEmailData] = useState(''); - const [listPath, setListPath] = useStateWithStorage( - 'tcl-shopping-list-path', - null, - ); + const [listPath] = useStateWithStorage('tcl-shopping-list-path', null); - // const listPath = 't4XIww03JAXm1QWr6UPEebbLRl13/first list'; + const { user } = useAuth(); + const userId = user?.uid; + const userEmail = user?.email; const handleTextChange = (event) => { - setItemName(event.target.value); + switch (event.target.id) { + case 'item-name': + return setItemName(event.target.value); + case 'email-input': + return setEmailData(event.target.value); + } }; const handleChange = (event) => { @@ -55,6 +60,32 @@ export function ManageList() { [itemName, daysUntilNextPurchase, listPath], ); + const shareCurrentList = async () => { + const listShared = await shareList(listPath, userId, emailData); + + if (listShared === '!owner') { + alert('You cannot share the list you do not own.'); + } else if (listShared === 'shared') { + alert('List was shared with recipient.'); + } else { + alert( + "The list was not shared because the recipient's email address does not exist in the system.", + ); + } + }; + + const handleEmailInputSubmit = (event) => { + event.preventDefault(); + + if (userEmail === emailData) { + alert('You cannot share the list with yourself.'); + } else { + shareCurrentList(); + } + + setEmailData(''); + }; + return (