From f91adf750f844779fb00dd4fff4fa20ef70c90c6 Mon Sep 17 00:00:00 2001 From: Tushar Daiya Date: Sun, 15 Oct 2023 23:17:13 +0530 Subject: [PATCH] fixed bookmarks metadata fetching --- .../Sections/Bookmarks/BookmarkItemGrid.jsx | 563 ++++++++---------- .../Sections/Bookmarks/MoreFromUser.jsx | 2 +- src/pages/Bookmarks.jsx | 147 +++-- 3 files changed, 340 insertions(+), 372 deletions(-) diff --git a/src/components/Sections/Bookmarks/BookmarkItemGrid.jsx b/src/components/Sections/Bookmarks/BookmarkItemGrid.jsx index 9d9a9d9..2872e03 100644 --- a/src/components/Sections/Bookmarks/BookmarkItemGrid.jsx +++ b/src/components/Sections/Bookmarks/BookmarkItemGrid.jsx @@ -43,9 +43,9 @@ const BookmarkItemGrid = ({ deleteBookmark, toggleBookmarkPin, collectionName, + metaData, }) => { - const [jsonResponse, setJsonResponse] = useState({}); - + const [imgError, setImgError] = useState(false); // to see if checked or not const [checked, setChecked] = useState(false); const [openEditBookmarkModal, setOpenEditBookmarkModal] = useState(false); @@ -64,66 +64,6 @@ const BookmarkItemGrid = ({ } }, [isSelected]); - useEffect(() => { - const fetchData = async () => { - const apiUrl = `https://jsonlink.io/api/extract?url=${url}`; - const backupApiUrl = `https://api.dub.co/metatags?url=${url}`; - const backupLinkCollect = `https://dev.linkcollect.io/api/v1/analytics/getMetadata?url=${url}`; - - try { - // Make the primary API request - const response = await fetch(apiUrl); - - if (!response.ok) { - await fetchAndSetBackup(); - } else { - const data = await response.json(); - - // Check if data.images.length is 0 or if data.description is empty or doesn't exist - if (data?.images?.length === 0 || !data?.description) { - await fetchAndSetBackup(); - } - - setJsonResponse(data); - } - } catch (error) { - console.error('There was a problem with the fetch operation:', error); - } - }; - fetchData(); - - const fetchAndSetBackup = async () => { - // const backupApiUrl = `https://api.dub.co/metatags?url=${url}`; - const backupLinkCollect = `https://dev.linkcollect.io/api/v1/analytics/getMetadata?url=${url}`; - - // If the primary API request fails, fall back to the backup API - const backupResponse = await fetch(backupLinkCollect); - - if (!backupResponse.ok) { - throw new Error('Both API requests failed'); - } - - let data = { - images: [], - description: - 'This Link has no Description 😔, but hey do you know that with linkcollect you can save all tabs using just a command and share them with your friends like this collection ?', - }; - - const res = await backupResponse.json(); - - console.log(res); - - if (res.data.description) { - data.description = res.data.description; - } - if (res.data.images) { - data.images = res.data.images; - } - - setJsonResponse(data); - console.log('-', data.images[0]); - }; - }, [url, setJsonResponse]); const copyRef = useRef(); const bookmarkEditModalHandler = () => { @@ -209,218 +149,201 @@ const BookmarkItemGrid = ({ return ( <> - {jsonResponse && ( - <> - - - {/* adding z index 100 below solves notes problem, but creates problem in sorting */} -
setHovered(true)} - onMouseLeave={() => setHovered(false)} - > - {note && bookmarkNoteModal && ( - - )} - - + + {/* adding z index 100 below solves notes problem, but creates problem in sorting */} +
setHovered(true)} + onMouseLeave={() => setHovered(false)} + > + {note && bookmarkNoteModal && ( + + )} + + + {isPinned && ( +
- {isPinned && ( -
- {selectedMode === 'light' ? ( - - ) : ( - - )} -
+ {selectedMode === 'light' ? ( + + ) : ( + )} - {/*
+ )} + {/* */} - {note && !hovered && windowWidth > 1024 && ( -
- {windowWidth > 1280 ? ( - ' Note Attached' + {note && !hovered && windowWidth > 1024 && ( +
+ {windowWidth > 1280 ? ( + ' Note Attached' + ) : ( + <> + {selectedMode === 'light' ? ( + ) : ( - <> - {selectedMode === 'light' ? ( - - ) : ( - - )} - + )} -
+ )} - -
- {jsonResponse?.images?.[0] ? ( - { - setJsonResponse(prev => ({ - ...prev, - images: [], - })); - - // jsonResponse.images[0] = - // 'https://media.discordapp.net/attachments/1075034816849924166/1153938590192128040/Frame.jpg?ex=651e558f&is=651d040f&hm=dd966ebc52ebda4c53c4af3cb0cae55e02bad8c561f7f161307577a50d246e90&=&width=1934&height=1158'; - }} - className="object-cover w-full h-full rounded-t-md" - /> - ) : ( - - )} -
-
-
+ )} + +
+ {metaData?.images?.[0] && !imgError ? ( + { + setImgError(true); + + // jsonResponse.images[0] = + // 'https://media.discordapp.net/attachments/1075034816849924166/1153938590192128040/Frame.jpg?ex=651e558f&is=651d040f&hm=dd966ebc52ebda4c53c4af3cb0cae55e02bad8c561f7f161307577a50d246e90&=&width=1934&height=1158'; + }} + className="object-cover w-full h-full rounded-t-md" + /> + ) : ( + + )} +
+ +
+ +

- + {/* description */} + {metaData?.description ? ( +

+ {metaData.description} +

+ ) : ( +

-

+ )} + +


+ +
+
+ {/* Timestamp */} + faviconIcon +

+ Added {fromNow(updatedAt)} +

+
+ {!isStillOneBookmarkSelected && ( +
+ - {name} -

- {/* description */} - {jsonResponse?.description ? ( -

- {jsonResponse.description} -

- ) : ( -

- {name} -

- )} - -
- -
-
- {/* Timestamp */} - faviconIcon -

- Added {fromNow(updatedAt)} -

-
- {!isStillOneBookmarkSelected && ( -
- - {selectedMode === 'light' ? ( - - ) : ( - - )} - - {/* + ) : ( + + )} + + {/* } */} - {auth.isLoggedIn && isOwner && ( -
- + {clickedId === id && ( + + {popupActionMenu.map((menuItem, index) => ( + <> + - )} - - {clickedId === id && ( - - {popupActionMenu.map((menuItem, index) => ( - <> - - {index !== popupActionMenu.length - 1 && ( -
- )} - - ))} - - )} -
+ {index !== popupActionMenu.length - 1 && ( +
+ )} + + ))} + )}
)}
-
+ )}
- - )} +
+
); }; diff --git a/src/components/Sections/Bookmarks/MoreFromUser.jsx b/src/components/Sections/Bookmarks/MoreFromUser.jsx index 2465379..c812c06 100644 --- a/src/components/Sections/Bookmarks/MoreFromUser.jsx +++ b/src/components/Sections/Bookmarks/MoreFromUser.jsx @@ -67,7 +67,7 @@ const MoreFromUser = ({ collectionData, user }) => { > {userCollections ?.filter(collection => { - return collection._id !== collectionData.collectionData._id; + return collection._id !== collectionData._id; }) .map(collection => { return ( diff --git a/src/pages/Bookmarks.jsx b/src/pages/Bookmarks.jsx index 9955a61..e22bfee 100644 --- a/src/pages/Bookmarks.jsx +++ b/src/pages/Bookmarks.jsx @@ -45,7 +45,10 @@ const Bookmarks = ({ windowWidth }) => { //For handiling click event on the bookmarkItem const [clickedId, setClickedId] = useState(null); const auth = useSelector(state => state.auth); - const collectionData = useSelector(state => state.collectionData); + const collectionData = useSelector( + state => state.collectionData.collectionData + ); + const isFetching = useSelector(state => state.collectionData.isFetching); const dispatch = useDispatch(); const { @@ -54,10 +57,67 @@ const Bookmarks = ({ windowWidth }) => { toggleSortByDropdown, toggleViewDropdown, } = useDropdown(); + + const [metaData, setMetaData] = useState([]); useEffect(() => { dispatch(getBookmarks({ collectionId })); }, [collectionId]); + useEffect(() => { + if (!isFetching && collectionData._id === collectionId) { + metaDataFetch(); + } + }, [isFetching]); + async function fetchMetaData(url) { + let data = { + images: [], + description: + 'This Link has no Description 😔, but hey do you know that with linkcollect you can save all tabs using just a command and share them with your friends like this collection ?', + }; + const apiUrl = `https://jsonlink.io/api/extract?url=${url}`; + const backupLinkCollect = `https://dev.linkcollect.io/api/v1/analytics/getMetadata?url=${url}`; + try { + const response = await fetch(apiUrl); + if (!response.ok) { + const backupResponse = await fetch(backupLinkCollect); + if (!backupResponse.ok) { + return data; + } + const res = await backupResponse.json(); + if (res.description) { + data.description = res.description; + } + if (res.images) { + data.images = res.images; + } + return data; + } + const res = await response.json(); + if (res.description) { + data.description = res.description; + } + if (res.images) { + data.images = res.images; + } + + return data; + } catch (err) { + console.log(err); + return data; + } + } + const metaDataFetch = async () => { + const fetchMetaDataPromises = collectionData.timelines.map( + async timeline => { + const metaData = await fetchMetaData(timeline.link); + return metaData; + } + ); + + const updatedTimeline = await Promise.all(fetchMetaDataPromises); + setMetaData(updatedTimeline); + }; + const editCollectionModalHandler = () => { setEditCollectionModalOpen(prev => !prev); }; @@ -138,67 +198,58 @@ const Bookmarks = ({ windowWidth }) => { // Logic for search const filteredBookmarks = useMemo(() => { - return !collectionData.isFetching && - collectionData.collectionData.timelines?.length > 0 - ? collectionData.collectionData.timelines.filter(tItem => + return !isFetching && collectionData.timelines?.length > 0 + ? collectionData.timelines.filter(tItem => tItem.title.toLowerCase().includes(query.toLowerCase()) ) : []; - }, [query, collectionData.collectionData, collectionData.isFetching]); + }, [query, collectionData, isFetching]); // dark and light mode switch const { selectedMode } = useContext(switchMode); return (
{/* Collection Edit Modal */} - {!collectionData.isFetching && ( + {!isFetching && ( )} - {!collectionData.isFetching && ( + {!isFetching && ( )} {/* Bookmarks */} {/* Create Bookamrk */} - {!collectionData.isFetching && ( + {!isFetching && ( { {/* Search Bar and Filter */}
@@ -256,17 +307,16 @@ const Bookmarks = ({ windowWidth }) => { {/* Bookmarks Container */}
- {collectionData.isFetching ? ( + {isFetching ? (
- ) : collectionData.collectionData && - filteredBookmarks?.length > 0 ? ( + ) : collectionData && filteredBookmarks?.length > 0 ? ( isGridView === 'GRID_VIEW' ? (
- {filteredBookmarks.map(timeline => ( + {filteredBookmarks.map((timeline, index) => ( { favicon={timeline.favicon} windowWidth={windowWidth} updatedAt={timeline.updatedAt} - isOwner={ - collectionData.collectionData.userId === auth.userId - } + isOwner={collectionData?.userId === auth.userId} clickedId={clickedId} setClickedId={setClickedId} isSelected={timeline.isSelected} collectionId={collectionId} toggleBookmarkPin={toggleBookmarkPin} isPinned={timeline.isPinned} - collectionName={collectionData.collectionData.title} + collectionName={collectionData?.title} + metaData={metaData[index]} /> ))}
@@ -304,16 +353,14 @@ const Bookmarks = ({ windowWidth }) => { favicon={timeline.favicon} windowWidth={windowWidth} updatedAt={timeline.updatedAt} - isOwner={ - collectionData.collectionData.userId === auth.userId - } + isOwner={collectionData?.userId === auth.userId} clickedId={clickedId} setClickedId={setClickedId} isSelected={timeline.isSelected} collectionId={collectionId} toggleBookmarkPin={toggleBookmarkPin} isPinned={timeline.isPinned} - collectionName={collectionData.collectionData.title} + collectionName={collectionData?.title} /> ))}
@@ -351,10 +398,10 @@ const Bookmarks = ({ windowWidth }) => { )}
- {!collectionData.isFetching && ( + {isFetching && ( )}