From 58616d391943988c9895111d0bcc860656165e3a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?K=C3=A9vin=20Cocchi?= <kevin.cocchi@gmail.com>
Date: Thu, 25 May 2023 23:09:11 +0200
Subject: [PATCH] Have _loadPacks return the fetched packs

---
 web/src/index.js | 31 +++++++++++++++++++------------
 1 file changed, 19 insertions(+), 12 deletions(-)

diff --git a/web/src/index.js b/web/src/index.js
index ce996f5..0e9792e 100644
--- a/web/src/index.js
+++ b/web/src/index.js
@@ -163,9 +163,16 @@ class App extends Component {
 		this._loadPacks(true)
 	}
 
+	async populateStickersByID(allPacks) {
+		const allStickers = allPacks.map(({ stickers }) => stickers).flat()
+		allStickers.forEach((sticker) => {
+			this.stickersByID.set(sticker.id, sticker)
+		})
+	}
+
 	_loadPacks(disableCache = false) {
 		const cache = disableCache ? "no-cache" : undefined
-		fetch(INDEX, {cache}).then(async indexRes => {
+		return fetch(INDEX, { cache }).then(async indexRes => {
 			if (indexRes.status >= 400) {
 				this.setState({
 					loading: false,
@@ -174,30 +181,30 @@ class App extends Component {
 				return
 			}
 			const indexData = await indexRes.json()
+			const packNames = indexData.packs ?? []
 			HOMESERVER_URL = indexData.homeserver_url || HOMESERVER_URL
 			HOMESERVER_ANIMATED_URL = indexData.homeserver_animated_url || HOMESERVER_URL
 			if (indexData.giphy_api_key !== undefined) {
 				setGiphyAPIKey(indexData.giphy_api_key, indexData.giphy_mxc_prefix)
 			}
 			// TODO only load pack metadata when scrolled into view?
-			for (const packFile of indexData.packs) {
+			const fetchedPacks = await Promise.all(packNames.map(async packFile => {
 				let packRes
 				if (packFile.startsWith("https://") || packFile.startsWith("http://")) {
 					packRes = await fetch(packFile, {cache})
 				} else {
 					packRes = await fetch(`${PACKS_BASE_URL}/${packFile}`, {cache})
 				}
-				const packData = await packRes.json()
-				for (const sticker of packData.stickers) {
-					this.stickersByID.set(sticker.id, sticker)
-				}
-				this.setState({
-					packs: [...this.state.packs, packData],
-					loading: false,
-				})
-			}
+				return await packRes.json()
+			}))
+			this.setState({
+				packs: fetchedPacks,
+				loading: false,
+			})
+			this.populateStickersByID(fetchedPacks)
 			this.updateFrequentlyUsed()
-		}, error => this.setState({loading: false, error}))
+			return fetchedPacks
+		}, error => this.setState({ loading: false, error }))
 	}
 
 	componentDidMount() {
-- 
GitLab