diff --git a/src/routes/stocks/[tickerID]/+layout.svelte b/src/routes/stocks/[tickerID]/+layout.svelte index 9b5acb63..dddc2da5 100644 --- a/src/routes/stocks/[tickerID]/+layout.svelte +++ b/src/routes/stocks/[tickerID]/+layout.svelte @@ -112,32 +112,51 @@ function handleTypeOfTrade(state:string) async function toggleUserWatchlist(watchListId: string) { try { const watchlistIndex = userWatchList?.findIndex((item) => item?.id === watchListId); - const postData = { - 'userId': data?.user?.id, - 'watchListId': watchListId, - 'ticker': $stockTicker, - 'path': 'update-watchlist' - }; - const response = await fetch('/api/fastify-post-data', { - method: 'POST', - headers: { - "Content-Type": "application/json" - }, - body: JSON.stringify(postData), - }); + + if (watchlistIndex !== -1) { + const tickerIndex = userWatchList[watchlistIndex]?.ticker?.indexOf($stockTicker); + + if (tickerIndex !== -1) { + // Remove the ticker if it exists + userWatchList[watchlistIndex]?.ticker?.splice(tickerIndex, 1); + } else { + // Add the ticker if it doesn't exist + userWatchList[watchlistIndex]?.ticker?.push($stockTicker); + } + } else { + userWatchList.push({'title': 'Favorites', 'ticker': [$stockTicker]}); + } + + + const postData = { + 'userId': data?.user?.id, + 'watchListId': watchListId, + 'ticker': $stockTicker, + 'path': 'update-watchlist' + }; + + const response = await fetch('/api/fastify-post-data', { + method: 'POST', + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify(postData), + }); if (!response.ok) { throw new Error("Network response was not ok"); } const output = (await response.json())?.items; - + /* if (watchlistIndex !== -1) { userWatchList[watchlistIndex] = output; } else { userWatchList.push(output); } + */ + userWatchList = [...userWatchList]; isTickerIncluded = !isTickerIncluded; @@ -829,11 +848,10 @@ function handleTypeOfTrade(state:string) ic_fluent_checkmark_circle_48_filled Created with Sketch. - +