Gracefully handle backend failures in Expo app

This commit is contained in:
Adolfo Reyna
2026-02-20 19:25:38 -05:00
parent fe9fc8e3e4
commit 009f1ec792
14 changed files with 205 additions and 97 deletions

117
API.js
View File

@@ -1,6 +1,38 @@
const baseUrl = "https://emiapi.reynafamily.com"; const baseUrl = "https://emiapi.reynafamily.com";
//const baseUrl = "http://localhost:3000"; //const baseUrl = "http://localhost:3000";
const requestErrorCooldownMs = 30000;
const profileFailureCooldownMs = 60000;
const recentRequestErrors = {};
const failedProfileCache = {};
const normalizePath = (path = "") => {
return path.replace(/[a-f0-9]{24}/gi, ":id");
};
const logRequestErrorOnce = (key, message) => {
const now = Date.now();
if (recentRequestErrors[key] && now - recentRequestErrors[key] < requestErrorCooldownMs) return;
recentRequestErrors[key] = now;
console.error(message);
};
const getFallbackForPath = (path = "") => {
if (path.startsWith("/post/") || path === "/post/") return [];
return {};
};
const parseJsonResponse = async (response, path = "", fallback) => {
const text = await response.text();
if (!text) return fallback;
try {
return JSON.parse(text);
} catch (error) {
const normalizedPath = normalizePath(path);
logRequestErrorOnce(`invalid-json:${normalizedPath}`, `Invalid JSON from ${normalizedPath}: ${text.slice(0, 200)}`);
return fallback;
}
};
let getCall = async (path = "", params = {}) => { let getCall = async (path = "", params = {}) => {
let queryParams = "?"; let queryParams = "?";
@@ -8,6 +40,7 @@ let getCall = async (path = "", params = {}) => {
queryParams += p + "=" + params[p] + "&" queryParams += p + "=" + params[p] + "&"
}); });
let localBaseUrl = global.baseUrl ?? baseUrl; let localBaseUrl = global.baseUrl ?? baseUrl;
const fallback = getFallbackForPath(path);
return fetch(localBaseUrl + path + queryParams, { return fetch(localBaseUrl + path + queryParams, {
method: 'GET', method: 'GET',
mode: 'cors', mode: 'cors',
@@ -15,9 +48,17 @@ let getCall = async (path = "", params = {}) => {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
} }
}).then(response => response.json()).catch((error) => { }).then(async (response) => {
console.error(error); const normalizedPath = normalizePath(path);
console.trace(); if (!response.ok) {
logRequestErrorOnce(`GET:${normalizedPath}:${response.status}`, `GET ${normalizedPath} failed: ${response.status}`);
return fallback;
}
return parseJsonResponse(response, path, fallback);
}).catch((error) => {
const normalizedPath = normalizePath(path);
logRequestErrorOnce(`GET:${normalizedPath}:network`, `GET ${normalizedPath} network error: ${error?.message || error}`);
return fallback;
}) })
} }
@@ -27,6 +68,7 @@ let deleteCall = async (path = "", params = {}) => {
queryParams += p + "=" + params[p] + "&" queryParams += p + "=" + params[p] + "&"
}); });
let localBaseUrl = global.baseUrl ?? baseUrl; let localBaseUrl = global.baseUrl ?? baseUrl;
const fallback = {};
return fetch(localBaseUrl + path + queryParams, { return fetch(localBaseUrl + path + queryParams, {
method: 'DELETE', method: 'DELETE',
mode: 'cors', mode: 'cors',
@@ -34,14 +76,23 @@ let deleteCall = async (path = "", params = {}) => {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
} }
}).then(response => response.json()).catch((error) => { }).then(async (response) => {
console.error(error); const normalizedPath = normalizePath(path);
console.trace(); if (!response.ok) {
logRequestErrorOnce(`DELETE:${normalizedPath}:${response.status}`, `DELETE ${normalizedPath} failed: ${response.status}`);
return fallback;
}
return parseJsonResponse(response, path, fallback);
}).catch((error) => {
const normalizedPath = normalizePath(path);
logRequestErrorOnce(`DELETE:${normalizedPath}:network`, `DELETE ${normalizedPath} network error: ${error?.message || error}`);
return fallback;
}) })
} }
let postCall = async (path, params) => { let postCall = async (path, params) => {
let localBaseUrl = global.baseUrl ?? baseUrl; let localBaseUrl = global.baseUrl ?? baseUrl;
const fallback = {};
return fetch(localBaseUrl + path, { return fetch(localBaseUrl + path, {
method: 'POST', method: 'POST',
mode: 'cors', mode: 'cors',
@@ -50,9 +101,17 @@ let postCall = async (path, params) => {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
} }
}).then(response => response.json()).catch((error) => { }).then(async (response) => {
console.error(error); const normalizedPath = normalizePath(path);
console.trace(); if (!response.ok) {
logRequestErrorOnce(`POST:${normalizedPath}:${response.status}`, `POST ${normalizedPath} failed: ${response.status}`);
return fallback;
}
return parseJsonResponse(response, path, fallback);
}).catch((error) => {
const normalizedPath = normalizePath(path);
logRequestErrorOnce(`POST:${normalizedPath}:network`, `POST ${normalizedPath} network error: ${error?.message || error}`);
return fallback;
}) })
} }
@@ -61,14 +120,44 @@ let CurrentProfile;
let CurrentProfileData; let CurrentProfileData;
let userNameCache = {}; //save this on localstorage let userNameCache = {}; //save this on localstorage
let working_on = {}; //Promises let working_on = {}; //Promises
const emptyProfileData = (id = "") => ({
_id: id || "",
profile: {
firstName: "",
lastName: "",
photo: "",
description: "",
language: "en",
},
data: {},
following: [],
});
let getProfileFromCache = async (id, refresh=false) => { let getProfileFromCache = async (id, refresh=false) => {
if(!id) console.trace(); if(!id) console.trace();
const lastFailure = failedProfileCache[id] || 0;
if (!refresh && lastFailure && Date.now() - lastFailure < profileFailureCooldownMs) {
return emptyProfileData(id);
}
if (userNameCache[id] && !refresh) if (userNameCache[id] && !refresh)
return userNameCache[id]; return userNameCache[id];
if (working_on[id] && !refresh) if (working_on[id] && !refresh)
return working_on[id]; return working_on[id];
//console.log(id, "not in cache, getting...") working_on[id] = getCall("/user/" + id).then((profile) => {
working_on[id] = getCall("/user/" + id) const hasRealProfile = !!(profile && profile._id);
const safeProfile = hasRealProfile ? { ...emptyProfileData(id), ...profile, profile: { ...emptyProfileData(id).profile, ...(profile.profile || {}) } } : emptyProfileData(id);
if (hasRealProfile) {
userNameCache[id] = safeProfile;
delete failedProfileCache[id];
} else {
failedProfileCache[id] = Date.now();
}
delete working_on[id];
return safeProfile;
}).catch(() => {
failedProfileCache[id] = Date.now();
delete working_on[id];
return emptyProfileData(id);
});
return working_on[id]; return working_on[id];
} }
@@ -140,8 +229,8 @@ const API = {
}, },
//Posts //Posts
getPosts(userid) { getPosts(userid) {
if (userid) return getCall("/post/usr/" + userid); if (userid) return getCall("/post/usr/" + userid).then((data) => Array.isArray(data) ? data : []);
return getCall("/post/"); return getCall("/post/").then((data) => Array.isArray(data) ? data : []);
}, },
getPostsByTag(tag) { getPostsByTag(tag) {
return getCall("/post/tag/" + tag); return getCall("/post/tag/" + tag);
@@ -235,7 +324,7 @@ const API = {
}); });
}, },
getUserProfile(profileid, refresh=false) { getUserProfile(profileid, refresh=false) {
return getProfileFromCache(profileid, refresh); return getProfileFromCache(profileid, refresh).then((profile) => profile || emptyProfileData(profileid));
}, },
deleteProfile(profileid){ deleteProfile(profileid){
return deleteCall("/user/" + profileid); return deleteCall("/user/" + profileid);

1
App.js
View File

@@ -102,6 +102,7 @@ const MainNavigation = ({ route }) => {
registerForPushNotificationsAsync().then(async (token) => { registerForPushNotificationsAsync().then(async (token) => {
let isLoggedIn = await API.isLoggedIn(); let isLoggedIn = await API.isLoggedIn();
if (!isLoggedIn) return false; if (!isLoggedIn) return false;
if (!token) return false;
API.registerToken(token); API.registerToken(token);
return setExpoPushToken(token); return setExpoPushToken(token);
}); });

View File

@@ -142,7 +142,7 @@ const Courses = () => {
horizontal={true} horizontal={true}
data={watching} data={watching}
renderItem={watchingCourse} renderItem={watchingCourse}
keyExtractor={item => item.profile._id} keyExtractor={(item, index) => item?.profile?._id || item?._id || `watching-${index}`}
initialNumToRender={2} initialNumToRender={2}
/> />
</View> : <></> </View> : <></>

View File

@@ -49,6 +49,7 @@ const handleURL = (url, navigation) => {
} }
async function onFetchUpdateAsync() { async function onFetchUpdateAsync() {
if (__DEV__) return;
try { try {
const update = await Updates.checkForUpdateAsync(); const update = await Updates.checkForUpdateAsync();
@@ -90,11 +91,11 @@ let Feed = ({ navigation, route }) => {
} }
if (!route.params?.reRender) { if (!route.params?.reRender) {
API.getMe().then((me) => { API.getMe().then((me) => {
if (subscribed) { if (subscribed && me && me._id) {
GlobalState.me = me; GlobalState.me = me;
posthog.identify(me.userid, posthog.identify(me.userid,
{ {
name: me.profile.firstName, name: me.profile?.firstName,
profileid: me._id, profileid: me._id,
is_superuser: me.superuser, is_superuser: me.superuser,
} }
@@ -108,11 +109,12 @@ let Feed = ({ navigation, route }) => {
console.log("Feed from server") console.log("Feed from server")
} }
await onFetchUpdateAsync(); await onFetchUpdateAsync();
flatListRef.current.scrollToOffset({ animated: true, offset: 0 }) flatListRef.current?.scrollToOffset({ animated: true, offset: 0 })
let posts = await API.getPosts(); let posts = await API.getPosts();
if (subscribed) { if (subscribed) {
setPosts(posts); const safePosts = Array.isArray(posts) ? posts : [];
storeFeed(posts); setPosts(safePosts);
storeFeed(safePosts);
} }
console.log("Feed, end useEffect") console.log("Feed, end useEffect")
} }
@@ -141,7 +143,7 @@ let Feed = ({ navigation, route }) => {
//ListHeaderComponent={<NewPost newPostCB={(newPost) => setPosts([newPost, ...Posts])} />} //ListHeaderComponent={<NewPost newPostCB={(newPost) => setPosts([newPost, ...Posts])} />}
refreshing={Posts.length === 0} refreshing={Posts.length === 0}
onRefresh={() => { onRefresh={() => {
API.getPosts().then(setPosts); API.getPosts().then((data) => setPosts(Array.isArray(data) ? data : []));
}} }}
initialNumToRender={3} initialNumToRender={3}
maxToRenderPerBatch={3} maxToRenderPerBatch={3}

View File

@@ -24,7 +24,7 @@ let MenuView = ({ navigation }) => {
let getData = async () => { let getData = async () => {
const r = await API.getMyProfiles(); const r = await API.getMyProfiles();
if (!subscribed) return; if (!subscribed) return;
setMyProfiles(r.profiles); setMyProfiles(Array.isArray(r?.profiles) ? r.profiles : []);
} }
getData(); getData();
return () => { return () => {
@@ -40,16 +40,17 @@ let MenuView = ({ navigation }) => {
//reloadAppAsync(); //reloadAppAsync();
} }
const profileLists = myProfiles.map((profile) => { const profileLists = myProfiles.map((profile) => {
const profileInfo = profile?.profile || {};
const DefaultPhoto = "https://social.emmint.com/uploads/e6f9be6d665dc43417701bf16a90122c.png"; const DefaultPhoto = "https://social.emmint.com/uploads/e6f9be6d665dc43417701bf16a90122c.png";
let photoUrl = profile.profile?.photo ? 'https://social.emmint.com/' + profile.profile.photo : DefaultPhoto; let photoUrl = profileInfo.photo ? 'https://social.emmint.com/' + profileInfo.photo : DefaultPhoto;
let icon = profile._id ? (!profile.isGroup ? "person-outline" : "group") : ''; let icon = profile._id ? (!profile.isGroup ? "person-outline" : "group") : '';
icon = icon === "person-outline" && profile.subscription && profile.subscription > (new Date() - 0) ? "assignment-ind" : icon; icon = icon === "person-outline" && profile.subscription && profile.subscription > (new Date() - 0) ? "assignment-ind" : icon;
icon = icon === "group" && profile.isCourse ? "subscriptions" : icon; icon = icon === "group" && profile.isCourse ? "subscriptions" : icon;
icon = icon === "group" && profile.isPrivate ? "screen-lock-portrait" : icon; icon = icon === "group" && profile.isPrivate ? "screen-lock-portrait" : icon;
return <> return <>
<List.Item <List.Item
title={profile.profile.firstName + " " + profile.profile.lastName} title={(profileInfo.firstName || "") + " " + (profileInfo.lastName || "")}
description={profile.profile.description} description={profileInfo.description || ""}
onPress={async () => { onPress={async () => {
await API.changeProfile(profile._id); await API.changeProfile(profile._id);
GlobalState.me = await API.getMe(); GlobalState.me = await API.getMe();

View File

@@ -44,16 +44,17 @@ let Profile = ({ navigation, route }) => {
console.log('Loading Cache Profile:' + route.params.profileid); console.log('Loading Cache Profile:' + route.params.profileid);
await API.getUserProfile(route.params.profileid).then((profileObj) => { await API.getUserProfile(route.params.profileid).then((profileObj) => {
if(!subscribed) return 0; if(!subscribed) return 0;
let profile = profileObj.profile const nextProfile = profileObj && profileObj._id ? profileObj : {};
setProfile(profileObj); const profileData = nextProfile.profile || {};
navigation.setOptions({ title: profile.firstName + " " + profile.lastName }); setProfile(nextProfile);
navigation.setOptions({ title: (profileData.firstName || "") + " " + (profileData.lastName || "") });
}); });
await getProfilePosts(route.params.profileid).then(setPosts); await getProfilePosts(route.params.profileid).then(setPosts);
console.log('Loaded Cache Profile:' + route.params.profileid); console.log('Loaded Cache Profile:' + route.params.profileid);
API.getPosts(route.params.profileid).then((data) => { API.getPosts(route.params.profileid).then((data) => {
setLoading(false); setLoading(false);
if(!subscribed) return 0; if(!subscribed) return 0;
setPosts(data); setPosts(Array.isArray(data) ? data : []);
storeProfilePosts(route.params.profileid, data); storeProfilePosts(route.params.profileid, data);
console.log('Store Cache Profile:' + route.params.profileid); console.log('Store Cache Profile:' + route.params.profileid);
}); });
@@ -62,7 +63,7 @@ let Profile = ({ navigation, route }) => {
console.log('Getting posts with tag', tag) console.log('Getting posts with tag', tag)
API.getPostsWithTag(route.params.profileid, tag).then((data) => { API.getPostsWithTag(route.params.profileid, tag).then((data) => {
if(!subscribed) return 0; if(!subscribed) return 0;
setPosts(data.posts); setPosts(Array.isArray(data?.posts) ? data.posts : []);
}); });
} else { } else {
// if no profile information is pressent should load feed // if no profile information is pressent should load feed
@@ -80,7 +81,7 @@ let Profile = ({ navigation, route }) => {
API.getPostsWithTag(tag).then((data) => { API.getPostsWithTag(tag).then((data) => {
//if(!subscribed) return 0; //if(!subscribed) return 0;
console.log(data.posts); console.log(data.posts);
setPosts(data.posts); setPosts(Array.isArray(data?.posts) ? data.posts : []);
}); });
} }
@@ -148,7 +149,7 @@ let Profile = ({ navigation, route }) => {
maxToRenderPerBatch={3} maxToRenderPerBatch={3}
removeClippedSubviews={true} removeClippedSubviews={true}
onRefresh={() => { onRefresh={() => {
API.getPosts(route.params.profileid).then(setPosts); API.getPosts(route.params.profileid).then((data) => setPosts(Array.isArray(data) ? data : []));
}} }}
/> : /> :
<></> //TODO: Add empty profile card here <></> //TODO: Add empty profile card here

View File

@@ -16,13 +16,14 @@ import * as ImagePicker from 'expo-image-picker';
let ProfileSettings = () => { let ProfileSettings = () => {
const gState = useSnapshot(GlobalState); const gState = useSnapshot(GlobalState);
const viewer = gState.me; const viewer = gState.me;
const viewerProfile = viewer?.profile || {};
const [photo, setPhoto] = React.useState(null); const [photo, setPhoto] = React.useState(null);
const [name, setName] = React.useState(viewer.profile.firstName); const [name, setName] = React.useState(viewerProfile.firstName || "");
const [lastName, setLastName] = React.useState(viewer.profile.lastName); const [lastName, setLastName] = React.useState(viewerProfile.lastName || "");
const [photoUrl, setphotoUrl] = React.useState(viewer.profile.photo); const [photoUrl, setphotoUrl] = React.useState(viewerProfile.photo || "");
const [language, setLanguage] = React.useState(viewer.profile.language); const [language, setLanguage] = React.useState(viewerProfile.language || "en");
const [updateKey, setUpdateKey] = React.useState(0); const [updateKey, setUpdateKey] = React.useState(0);
const [description, setDescription] = React.useState(viewer.profile.description); const [description, setDescription] = React.useState(viewerProfile.description || "");
const [uploading, setUploading] = React.useState(false); const [uploading, setUploading] = React.useState(false);
const pickImage = async () => { const pickImage = async () => {
@@ -41,6 +42,7 @@ let ProfileSettings = () => {
let newPhotoURL = await handleUploadPhoto(result.assets[0]); let newPhotoURL = await handleUploadPhoto(result.assets[0]);
if (newPhotoURL !== "") { if (newPhotoURL !== "") {
setphotoUrl(newPhotoURL); setphotoUrl(newPhotoURL);
if (!GlobalState.me.profile) GlobalState.me.profile = {};
GlobalState.me.profile.photo = newPhotoURL; GlobalState.me.profile.photo = newPhotoURL;
updateProfile() updateProfile()
setUpdateKey(updateKey + 1); setUpdateKey(updateKey + 1);
@@ -90,9 +92,9 @@ let ProfileSettings = () => {
}; };
let updateProfile = async () => { let updateProfile = async () => {
let currentProfile = await API.getUserProfile(viewer._id) let currentProfile = await API.getUserProfile(viewer?._id);
currentData = currentProfile.data; const currentData = currentProfile?.data || {};
currentProfile = currentProfile.profile; currentProfile = currentProfile?.profile || {};
try { try {
//let currentProfile = JSON.parse(JSON.stringify(viewer.profile)); //let currentProfile = JSON.parse(JSON.stringify(viewer.profile));
currentProfile.firstName = name; currentProfile.firstName = name;

View File

@@ -29,12 +29,16 @@ const getName = async (key) => {
let CourseCard = ({ profileid, hideIcon, profileObj, twoCols }) => { let CourseCard = ({ profileid, hideIcon, profileObj, twoCols }) => {
let [profile, setProfile] = useState(profileObj || {}); let [profile, setProfile] = useState(profileObj || {});
const safeProfile = profile || {};
const safeProfileInfo = safeProfile.profile || {};
const safeProfileObj = profileObj || {};
const safeProfileObjInfo = safeProfileObj.profile || {};
const navigation = useNavigation(); const navigation = useNavigation();
useEffect(() => { useEffect(() => {
let subscribed = true; let subscribed = true;
const getData = async () => { const getData = async () => {
if (profileObj._id) return 0; if (safeProfileObj._id) return 0;
let cacheProfile = await getName(profileid); let cacheProfile = await getName(profileid);
if (cacheProfile && cacheProfile.profile) setProfile(cacheProfile); if (cacheProfile && cacheProfile.profile) setProfile(cacheProfile);
let p = await API.getUserProfile(profileid).catch(() => { return {} }); let p = await API.getUserProfile(profileid).catch(() => { return {} });
@@ -47,13 +51,13 @@ let CourseCard = ({ profileid, hideIcon, profileObj, twoCols }) => {
} }
}, [profileid]); }, [profileid]);
let icon = profile._id ? (!profile.isGroup ? "person-outline" : "group") : ''; let icon = safeProfile._id ? (!safeProfile.isGroup ? "person-outline" : "group") : '';
icon = icon === "person-outline" && profile.subscription && profile.subscription > (new Date() - 0) ? "assignment-ind" : icon; icon = icon === "person-outline" && safeProfile.subscription && safeProfile.subscription > (new Date() - 0) ? "assignment-ind" : icon;
icon = icon === "group" && profile.isCourse ? "subscriptions" : icon; icon = icon === "group" && safeProfile.isCourse ? "subscriptions" : icon;
let photoUrl = profile.data && profile.data.profileImg ? profile.data.profileImg : DefaultPhoto; let photoUrl = safeProfile.data && safeProfile.data.profileImg ? safeProfile.data.profileImg : DefaultPhoto;
const onPress = () => { const onPress = () => {
return navigation.navigate('Profile', { profileid: profile._id }) return navigation.navigate('Profile', { profileid: safeProfile._id })
} }
return ( return (
@@ -64,28 +68,28 @@ let CourseCard = ({ profileid, hideIcon, profileObj, twoCols }) => {
{!hideIcon ? <Icon name={icon} size={18} /> : <></>} {!hideIcon ? <Icon name={icon} size={18} /> : <></>}
</Text> </Text>
<Text> <Text>
{profile.profile && profile.profile.firstName} {profile.profile && profile.profile.lastName} {safeProfileInfo.firstName} {safeProfileInfo.lastName}
</Text> </Text>
</Title> </Title>
<Paragraph numberOfLines={2}> <Paragraph numberOfLines={2}>
{profileObj.profile.description ? profileObj.profile.description : "We are working on this course description, soon to come!"} {safeProfileObjInfo.description ? safeProfileObjInfo.description : "We are working on this course description, soon to come!"}
</Paragraph> </Paragraph>
{profile.data ? {safeProfile.data ?
<View style={{flexDirection: "row", marginTop:5}}> <View style={{flexDirection: "row", marginTop:5}}>
<Avatar.Image size={64} source={{ uri: photoUrl }} /> <Avatar.Image size={64} source={{ uri: photoUrl }} />
<View> <View>
<Text>By: {profile.data.author ? profile.data.author : 'Working on this'}</Text> <Text>By: {safeProfile.data.author ? safeProfile.data.author : 'Working on this'}</Text>
<Text> <Text>
<Icon name="date-range" /> <Icon name="date-range" />
{profile.data.year ? profile.data.year : 'XXXX'} {safeProfile.data.year ? safeProfile.data.year : 'XXXX'}
</Text> </Text>
<Text> <Text>
<Icon name="timer" /> <Icon name="timer" />
{profile.data.duration ? profile.data.duration : '??'} {safeProfile.data.duration ? safeProfile.data.duration : '??'}
</Text> </Text>
<Text> <Text>
<Icon name="language" /> <Icon name="language" />
{profile.data.language} {safeProfile.data.language}
</Text> </Text>
</View> </View>
</View> </View>

View File

@@ -31,12 +31,16 @@ const getName = async (key) => {
let ProfileCard = ({ profileid, hideIcon, profileObj }) => { let ProfileCard = ({ profileid, hideIcon, profileObj }) => {
let [profile, setProfile] = useState(profileObj || {}); let [profile, setProfile] = useState(profileObj || {});
const safeProfile = profile || {};
const safeProfileInfo = safeProfile.profile || {};
const safeProfileObj = profileObj || {};
const safeProfileObjInfo = safeProfileObj.profile || {};
const navigation = useNavigation(); const navigation = useNavigation();
useEffect(() => { useEffect(() => {
let subscribed = true; let subscribed = true;
const getData = async () => { const getData = async () => {
if (profileObj._id) return 0; if (safeProfileObj._id) return 0;
let cacheProfile = await getName(profileid); let cacheProfile = await getName(profileid);
if (cacheProfile && cacheProfile.profile) setProfile(cacheProfile); if (cacheProfile && cacheProfile.profile) setProfile(cacheProfile);
let p = await API.getUserProfile(profileid).catch(() => { return {} }); let p = await API.getUserProfile(profileid).catch(() => { return {} });
@@ -49,14 +53,14 @@ let ProfileCard = ({ profileid, hideIcon, profileObj }) => {
} }
}, [profileid]); }, [profileid]);
let icon = profile._id ? (!profile.isGroup ? "person-outline" : "group") : ''; let icon = safeProfile._id ? (!safeProfile.isGroup ? "person-outline" : "group") : '';
icon = icon === "person-outline" && profile.subscription && profile.subscription > (new Date() - 0) ? "assignment-ind" : icon; icon = icon === "person-outline" && safeProfile.subscription && safeProfile.subscription > (new Date() - 0) ? "assignment-ind" : icon;
icon = icon === "group" && profile.isCourse ? "subscriptions" : icon; icon = icon === "group" && safeProfile.isCourse ? "subscriptions" : icon;
icon = icon === "group" && profile.isPrivate ? "screen-lock-portrait" : icon; icon = icon === "group" && safeProfile.isPrivate ? "screen-lock-portrait" : icon;
let photoUrl = profile.profile.photo ? 'https://social.emmint.com/' + profile.profile.photo : DefaultPhoto; let photoUrl = safeProfileInfo.photo ? 'https://social.emmint.com/' + safeProfileInfo.photo : DefaultPhoto;
const onPress = () => { const onPress = () => {
return navigation.navigate('Profile', { profileid: profile._id }) return navigation.navigate('Profile', { profileid: safeProfile._id })
} }
return ( return (
@@ -70,7 +74,7 @@ let ProfileCard = ({ profileid, hideIcon, profileObj }) => {
<List.Item <List.Item
title={<ProfilePhotoCircle profileid={profile._id} />} title={<ProfilePhotoCircle profileid={profile._id} />}
description={profileObj.profile.description} description={safeProfileObjInfo.description || ""}
//left={props => <List.Icon {...props} icon={icon} />} //left={props => <List.Icon {...props} icon={icon} />}
titleStyle={{fontWeight:"bold", fontSize:20}} titleStyle={{fontWeight:"bold", fontSize:20}}
descriptionStyle={{}} descriptionStyle={{}}

View File

@@ -1,6 +1,5 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Text, Pressable, FlatList, StyleSheet, View, Share, Alert, Linking } from 'react-native'; import { Text, Pressable, FlatList, StyleSheet, View, Share, Alert, Linking } from 'react-native';
import Hyperlink from 'react-native-hyperlink'
import { Button, Card, Chip } from 'react-native-paper'; import { Button, Card, Chip } from 'react-native-paper';
import API from './../API.js'; import API from './../API.js';
import UserName from './UserName.js'; import UserName from './UserName.js';

View File

@@ -1,6 +1,5 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Text, ScrollView, FlatList, StyleSheet, View, Share } from 'react-native'; import { Text, ScrollView, FlatList, StyleSheet, View, Share } from 'react-native';
import Hyperlink from 'react-native-hyperlink'
import { Button, Card, Chip } from 'react-native-paper'; import { Button, Card, Chip } from 'react-native-paper';
import API from '../API.js'; import API from '../API.js';
import UserName from './UserName.js'; import UserName from './UserName.js';
@@ -44,17 +43,15 @@ let Post = (props) => {
margin: 0, margin: 0,
marginBottom: 0 marginBottom: 0
}}> }}>
<Hyperlink linkDefault={true} linkStyle={{ color: '#2980b9' }}> <View>
<View> <Text style={{ fontSize: 18 }}>{cleanContent}</Text>
<Text style={{ fontSize: 18 }}>{cleanContent}</Text> <Media content={post.content} />
<Media content={post.content} /> <FlatList data={userIds}
<FlatList data={userIds} horizontal={true}
horizontal={true} renderItem={renderPost}
renderItem={renderPost} //keyExtractor={item => item}
//keyExtractor={item => item} />
/> </View>
</View>
</Hyperlink>
</Card.Content> </Card.Content>
</Card> </Card>
); );

View File

@@ -30,12 +30,16 @@ const getName = async (key) => {
let ProfileCard = ({ profileid, hideIcon, profileObj }) => { let ProfileCard = ({ profileid, hideIcon, profileObj }) => {
let [profile, setProfile] = useState(profileObj || {}); let [profile, setProfile] = useState(profileObj || {});
const safeProfile = profile || {};
const safeProfileInfo = safeProfile.profile || {};
const safeProfileObj = profileObj || {};
const safeProfileObjInfo = safeProfileObj.profile || {};
const navigation = useNavigation(); const navigation = useNavigation();
useEffect(() => { useEffect(() => {
let subscribed = true; let subscribed = true;
const getData = async () => { const getData = async () => {
if (profileObj._id) return 0; if (safeProfileObj._id) return 0;
let cacheProfile = await getName(profileid); let cacheProfile = await getName(profileid);
if (cacheProfile && cacheProfile.profile && subscribed) setProfile(cacheProfile); if (cacheProfile && cacheProfile.profile && subscribed) setProfile(cacheProfile);
let p = await API.getUserProfile(profileid).catch(() => { return {} }); let p = await API.getUserProfile(profileid).catch(() => { return {} });
@@ -48,13 +52,13 @@ let ProfileCard = ({ profileid, hideIcon, profileObj }) => {
} }
}, [profileid]); }, [profileid]);
let icon = profile._id ? (!profile.isGroup ? "person-outline" : "group") : ''; let icon = safeProfile._id ? (!safeProfile.isGroup ? "person-outline" : "group") : '';
icon = icon === "person-outline" && profile.subscription && profile.subscription > (new Date() - 0) ? "assignment-ind" : icon; icon = icon === "person-outline" && safeProfile.subscription && safeProfile.subscription > (new Date() - 0) ? "assignment-ind" : icon;
icon = icon === "group" && profile.isCourse ? "subscriptions" : icon; icon = icon === "group" && safeProfile.isCourse ? "subscriptions" : icon;
let photoUrl = profile.profile.photo ? 'https://social.emmint.com/' + profile.profile.photo : DefaultPhoto; let photoUrl = safeProfileInfo.photo ? 'https://social.emmint.com/' + safeProfileInfo.photo : DefaultPhoto;
const onPress = () => { const onPress = () => {
return navigation.navigate('Profile', { profileid: profile._id }) return navigation.navigate('Profile', { profileid: safeProfile._id })
} }
return ( return (
@@ -63,11 +67,11 @@ let ProfileCard = ({ profileid, hideIcon, profileObj }) => {
<Avatar.Image size={150} source={{ uri: photoUrl }} /> <Avatar.Image size={150} source={{ uri: photoUrl }} />
<Title onPress={onPress} numberOfLines={1}> <Title onPress={onPress} numberOfLines={1}>
<Text> <Text>
{profile.profile && profile.profile.firstName} {profile.profile && profile.profile.lastName} {safeProfileInfo.firstName} {safeProfileInfo.lastName}
</Text> </Text>
</Title> </Title>
<Paragraph numberOfLines={2}>{profileObj.profile.description}</Paragraph> <Paragraph numberOfLines={2}>{safeProfileObjInfo.description || ""}</Paragraph>
<FollowButton profile={profile} /> <FollowButton profile={safeProfile} />
</Card.Content> </Card.Content>
</Card> </Card>

View File

@@ -7,7 +7,9 @@ import FollowButton from './basics/FollowButton';
const DefaultPhoto = "https://social.emmint.com/uploads/e6f9be6d665dc43417701bf16a90122c.png"; const DefaultPhoto = "https://social.emmint.com/uploads/e6f9be6d665dc43417701bf16a90122c.png";
const ProfileHeader = ({ profileObj }) => { const ProfileHeader = ({ profileObj }) => {
let photoUrl = profileObj.profile && profileObj.profile.photo ? 'https://social.emmint.com/' + profileObj.profile.photo + '?width=1000&height=1000' : DefaultPhoto; const safeProfileObj = profileObj || {};
const safeProfile = safeProfileObj.profile || {};
let photoUrl = safeProfile.photo ? 'https://social.emmint.com/' + safeProfile.photo + '?width=1000&height=1000' : DefaultPhoto;
return ( return (
<> <>
<Card elevation={3}> <Card elevation={3}>
@@ -16,9 +18,9 @@ const ProfileHeader = ({ profileObj }) => {
}} /> }} />
<Card.Content style={{}}> <Card.Content style={{}}>
<Title style={{ position: "absolute", top: -60, left: 10, backgroundColor: "rgba(255,255,255,0.4)", padding: 10 }}> <Title style={{ position: "absolute", top: -60, left: 10, backgroundColor: "rgba(255,255,255,0.4)", padding: 10 }}>
<UserName profileid={profileObj._id} /> <UserName profileid={safeProfileObj._id} />
</Title> </Title>
<Paragraph style={{ paddingTop: 10 }}>{profileObj.profile.description}</Paragraph> <Paragraph style={{ paddingTop: 10 }}>{safeProfile.description || ""}</Paragraph>
<View style={{ <View style={{
position: "absolute", position: "absolute",
top: -290, top: -290,
@@ -29,7 +31,7 @@ const ProfileHeader = ({ profileObj }) => {
borderRadius: 25, borderRadius: 25,
opacity: 0.7 opacity: 0.7
}}> }}>
<FollowButton profile={profileObj} /> <FollowButton profile={safeProfileObj} />
</View> </View>
<View style={{ <View style={{
position: "absolute", position: "absolute",
@@ -43,8 +45,8 @@ const ProfileHeader = ({ profileObj }) => {
}}> }}>
<Button icon="ios-share" labelStyle={{ fontSize: 24, paddingTop:10 }} onPress={() => { <Button icon="ios-share" labelStyle={{ fontSize: 24, paddingTop:10 }} onPress={() => {
Share.share({ Share.share({
message: "https://social.emmint.com/feed/" + profileObj._id, message: "https://social.emmint.com/feed/" + safeProfileObj._id,
title: profileObj.profile.firstName + " " + profileObj.profile.lastName title: (safeProfile.firstName || "") + " " + (safeProfile.lastName || "")
}); });
}}></Button> }}></Button>
</View> </View>

View File

@@ -6,12 +6,14 @@ import UserName from './UserName';
const DefaultPhoto = "https://social.emmint.com/uploads/e6f9be6d665dc43417701bf16a90122c.png"; const DefaultPhoto = "https://social.emmint.com/uploads/e6f9be6d665dc43417701bf16a90122c.png";
const ProfileSmallHeader = ({ profileObj }) => { const ProfileSmallHeader = ({ profileObj }) => {
let photoUrl = profileObj.profile.photo ? 'https://social.emmint.com/' + profileObj.profile.photo : DefaultPhoto; const safeProfileObj = profileObj || {};
const safeProfile = safeProfileObj.profile || {};
let photoUrl = safeProfile.photo ? 'https://social.emmint.com/' + safeProfile.photo : DefaultPhoto;
return ( return (
<> <>
<Card.Title <Card.Title
title={<UserName profileid={profileObj._id} hideIcon={true} />} title={<UserName profileid={safeProfileObj._id} hideIcon={true} />}
subtitle={profileObj.profile.description} subtitle={safeProfile.description || ""}
left={(props) => <Avatar.Image {...props} source={{ uri: photoUrl}} />} left={(props) => <Avatar.Image {...props} source={{ uri: photoUrl}} />}
right={(props) => <IconButton {...props} icon="more-vert" onPress={() => { }} />} right={(props) => <IconButton {...props} icon="more-vert" onPress={() => { }} />}
/> />