Harden courses cache and viewer data iteration

This commit is contained in:
Adolfo Reyna
2026-02-20 20:18:27 -05:00
parent d2491800f2
commit 058b060d03
+35 -18
View File
@@ -8,28 +8,43 @@ import GlobalState from '../contexts/GlobalState.js';
import i18n from "../i18nMessages.js";
import AsyncStorage from '@react-native-async-storage/async-storage';
const getCourses = async (profileObj) => {
let courses;
let popular;
const emptyCoursesData = {
courses: [],
popular: [],
watching: [],
};
const getCourses = async (profileObj = {}) => {
let courses = [];
let popular = [];
await API.getCourses().then((data) => {
courses = data.groups;
popular = [...data.groups].sort((a, b) => {
const groups = Array.isArray(data?.groups) ? data.groups : [];
courses = groups;
popular = [...groups].sort((a, b) => {
return Object.keys(b.subscribed).length - Object.keys(a.subscribed).length;
});
});
let watching = {};
let watchingProms = [];
Object.keys(profileObj.data).forEach((videoId) => {
if (profileObj.data[videoId].profileId) {
let profileId = profileObj.data[videoId].profileId;
let viewerData = {};
try {
// Detach potential proxy/non-extensible objects before iterating keys.
viewerData = JSON.parse(JSON.stringify(profileObj?.data || {}));
} catch (error) {
viewerData = {};
}
Object.keys(viewerData).forEach((videoId) => {
const progress = viewerData[videoId];
if (progress?.profileId) {
let profileId = progress.profileId;
watchingProms.push(API.getUserProfile(profileId).then(profile => {
if (!profile.isCourse)
return 0;
if (!watching[profileId])
watching[profileId] = { profile, progress: [], mostRecent: 0 };
if (watching[profileId].mostRecent < profileObj.data[videoId].ts)
watching[profileId].mostRecent = profileObj.data[videoId].ts;
watching[profileId].progress.push(profileObj.data[videoId]);
if (watching[profileId].mostRecent < progress.ts)
watching[profileId].mostRecent = progress.ts;
watching[profileId].progress.push(progress);
}));
}
});
@@ -63,8 +78,9 @@ const getCoursesCache = async () => {
if (value !== null) {
return JSON.parse(value);
}
return emptyCoursesData;
} catch (e) {
return []
return emptyCoursesData;
}
}
@@ -80,12 +96,13 @@ const Courses = () => {
useEffect(() => {
let subscribed = true;
const getData = async () => {
await getCoursesCache().then((r) => {
console.log("Courses Cache");
setGroups(r.courses || []);
setPopular(r.popular || []);
setWatching(r.watching || []);
});
const cached = await getCoursesCache();
console.log("Courses Cache");
if (subscribed) {
setGroups(Array.isArray(cached?.courses) ? cached.courses : []);
setPopular(Array.isArray(cached?.popular) ? cached.popular : []);
setWatching(Array.isArray(cached?.watching) ? cached.watching : []);
}
let r = await getCourses(viewer);
console.log("Courses Live");
if(subscribed){