add a loading indicator while photos and videos are being loaded in react native
- User
add a loading indicator while photos and videos are being loaded in react native
- Assistant
- User
- Assistant
add a loading indicator while photos and videos are being loaded in react native
Adding a loading indicator while photos and videos are being loaded in a React Native app can enhance the user experience by informing users that content is being fetched. Here's a simple example of how you can implement this feature using the ActivityIndicator component from React Native.
Import Necessary Components:
You will need to import useState, useEffect, and ActivityIndicator from React and React Native.
Set Up State for Loading:
Use the useState hook to manage the loading state.
Fetch Data and Toggle Loading State:
Update the loading state before and after fetching your photos or videos.
Conditional Rendering:
Render the ActivityIndicator component while the data is being loaded.
Here's a basic example:
import React, { useState, useEffect } from 'react';
import { View, Text, ActivityIndicator, Image, StyleSheet, FlatList } from 'react-native';
const PhotoGallery = () => {
const [loading, setLoading] = useState(true);
const [photos, setPhotos] = useState([]);
useEffect(() => {
// Simulate an API call to fetch photos with a timeout
fetchPhotos();
}, []);
const fetchPhotos = async () => {
try {
// Simulating network request
setLoading(true); // Set loading to true before data fetch
// Replace the following line with actual API call to fetch data
const fakePhotos = await new Promise((resolve) =>
setTimeout(() => resolve([
'https://example.com/photo1.jpg',
'https://example.com/photo2.jpg',
// ... more photo URLs
]), 2000)
);
setPhotos(fakePhotos);
} catch (error) {
console.error('Error fetching photos:', error);
} finally {
setLoading(false); // Set loading to false after data fetch
}
};
if (loading) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#0000ff" />
<Text>Loading photos...</Text>
</View>
);
}
return (
<FlatList
data={photos}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
<View style={styles.photoContainer}>
<Image source={{ uri: item }} style={styles.photo} />
</View>
)}
/>
);
};
const styles = StyleSheet.create({
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
photoContainer: {
alignItems: 'center',
margin: 10,
},
photo: {
width: 100,
height: 100,
},
});
export default PhotoGallery;
useState Hook: The loading state is initially set to true and will remain true until the data is fetched.useEffect Hook: Used to fetch photos when the component mounts. Simulated here with a timeout.ActivityIndicator: Displays a spinning wheel during data loading. You can customize its size and color.FlatList: Once the data is fetched and the loading state is set to false, the list of images is rendered using FlatList, which is more performance-efficient for rendering lists in React Native.This pattern can be similarly used for loading videos or other types of content in your React Native application.
import { CryptoUtils, RandomUtils } from "@openchat/framework" import { AttachmentKindEnum, FileType, MessageKindEnum, MessageMetadataType, MessagePackType, MessageType, PollType, } from "@openchat/types" import { useAccountId, useChannel, useLogger, useMemberBy } from "@openchat/ui" import { useState } from "react" import { Pressable, View } from "react-native" import { isCancel, pick } from "react-native-document-picker" import { launchImageLibrary } from "react-native-image-picker" import { AppColors } from "../../../app/app-colors" import { AppControllers } from "../../../app/app-context" import { NavigationRef } from "../../../navigation/navigation.hooks" import { Icon } from "../../../ui-components/icon/icon.component" import { useModal } from "../../../ui-components/modal/modal.hook" import { StyledText } from "../../../ui-components/styled-text/styled-text" import { FileUtils } from "../../../utils/file/file.utils" import { useStyles } from "./message-input-popup.style" import { Region } from "react-native-maps" import { RoomUtils } from "@openchat/models"
export function MessageInputPopup({ roomId, onProfileSelect, onFilesSelected, onLocationSelect, isShowFileAndProfile = false, newMessagePacks, }: { roomId: string onProfileSelect: ( users: { id: string name: string photo: FileType | null }[], ) => void onLocationSelect: (coordinate: Region) => void onFilesSelected: (files: FileType[], kind: AttachmentKindEnum) => void isShowFileAndProfile?: boolean newMessagePacks: (messagePack: MessagePackType) => void }) { // --------------------------------------------------------------------------- // variables // ---------------------------------------------------------------------------
const logger = useLogger("MessageInputPopup") const modal = useModal() const accountId = useAccountId() const [files, setFiles] = useState<FileType[]>([]) const { communityId, channelId } = RoomUtils.extractIds(roomId) const channel = useChannel(channelId) const currentMember = useMemberBy({ communityId: communityId, identityId: accountId, }) const styles = useStyles() // --------------------------------------------------------------------------- // functions // ---------------------------------------------------------------------------
async function onGallerySelect() { const files = await launchImageLibrary({ mediaType: "mixed", includeBase64: true, includeExtra: true, selectionLimit: 0, })
if (!files.assets) return
const media: FileType[] = []
for (let selectedFile of files.assets) {
if (!selectedFile.uri) return
const blob = await fetch(selectedFile.uri).then((response) => {
return response.blob()
})
const file = await new Promise<FileType>((ok, fail) => {
const reader = new FileReader()
reader.onload = () => {
const dataUrl = reader.result as string
const file: FileType = {
id: CryptoUtils.sha256(dataUrl),
name: selectedFile.fileName ? selectedFile.fileName : "",
size: blob.size,
mimeType: blob.type,
data: dataUrl,
duration: null,
}
ok(file)
}
reader.onerror = fail
reader.readAsDataURL(blob)
})
media.push(file)
}
onFilesSelected(media, AttachmentKindEnum.media)
}
async function onFileSelect() { const files = await pick({ allowMultiSelection: true })
try {
const file = await FileUtils.builtFileType(files)
onFilesSelected(file, AttachmentKindEnum.file)
setFiles(file)
} catch (err) {
if (isCancel(err)) {
logger.log("Canceled: ", err)
} else {
logger.log(err)
}
}
}
async function save(poll: { isPrivate: boolean title: string isMultiple: boolean options: { id: string order: number name: string votedUserIds: string[] }[] }) { if (!accountId) return
const newPoll: PollType = {
id: RandomUtils.uuid(),
createdAt: Date.now(),
isMultiple: poll.isMultiple,
isPrivate: poll.isPrivate,
title: poll.title,
isClosed: false,
pollOptions: poll.options.filter((option) => option.name !== ""),
totalVotedUsersCount: 0,
roomId: roomId,
}
const metadata: MessageMetadataType = {
id: RandomUtils.uuid(),
replyCount: 0,
}
const newMessage: MessageType = {
id: RandomUtils.uuid(),
createdAt: Date.now(),
text: "",
roomId: roomId,
isEdited: false,
isDeleted: false,
isDelivered: false,
senderId: !currentMember ? accountId : null,
senderMemberId: currentMember ? currentMember.id : null,
reactions: [],
forward: null,
regular: {
kind: MessageKindEnum.poll,
quote: null,
sharedUser: null,
sticker: null,
location: null,
},
question: null,
answer: null,
news: null,
issue: null,
board: null,
}
newMessagePacks({
message: newMessage,
metadata,
links: [],
attachments: [],
files: [],
poll: newPoll,
})
await AppControllers.message.insert([
{
message: newMessage,
metadata,
attachments: [],
links: [],
files: [],
poll: newPoll,
},
])
}
// --------------------------------------------------------------------------- return ( {/* --------------------------------------------------------------------------- /} {/ SHARE IMAGE OR VIDEO /} {/ --------------------------------------------------------------------------- */}
{isShowFileAndProfile && (
<Pressable
onPress={() => {
modal.close()
onGallerySelect()
}}
style={({ pressed }) => [
pressed
? { backgroundColor: AppColors.backgroundDark }
: { backgroundColor: "white" },
styles.itemWrapper,
]}
>
{({ pressed }) => (
<>
<View
style={[
pressed
? { backgroundColor: AppColors.primary }
: { backgroundColor: AppColors.backgroundLight },
styles.iconWrapper,
]}
>
<Icon
name="fal fa-photo-film"
size={20}
fill={pressed ? "white" : AppColors.iconDefault}
/>
</View>
<StyledText style={styles.text}>Image & Video</StyledText>
</>
)}
</Pressable>
)}
{/* --------------------------------------------------------------------------- */}
{/* SHARE FILE */}
{/* --------------------------------------------------------------------------- */}
<Pressable
onPress={() => {
modal.close()
onFileSelect()
}}
style={({ pressed }) => [
pressed
? { backgroundColor: AppColors.backgroundDark }
: { backgroundColor: "white" },
styles.itemWrapper,
]}
>
{({ pressed }) => (
<>
<View
style={[
pressed
? { backgroundColor: AppColors.primary }
: { backgroundColor: AppColors.backgroundLight },
styles.iconWrapper,
]}
>
<Icon
name="fal fa-file"
size={20}
fill={pressed ? "white" : AppColors.iconDefault}
/>
</View>
<StyledText style={styles.text}>File</StyledText>
</>
)}
</Pressable>
{/* --------------------------------------------------------------------------- */}
{/* CREATE POLL */}
{/* --------------------------------------------------------------------------- */}
{isShowFileAndProfile && (
<>
{/* {channel && channel.isPollsEnabled && ( */}
<Pressable
onPress={() => {
modal.close()
NavigationRef.navigate("PollUpsert", {
onSend: (poll: any) => save(poll),
})
}}
style={({ pressed }) => [
pressed
? { backgroundColor: AppColors.backgroundDark }
: { backgroundColor: "white" },
styles.itemWrapper,
]}
>
{({ pressed }) => (
<>
<View
style={[
pressed
? { backgroundColor: AppColors.primary }
: { backgroundColor: AppColors.backgroundLight },
styles.iconWrapper,
]}
>
<Icon
name="fal fa-poll-people"
size={20}
fill={pressed ? "white" : AppColors.iconDefault}
/>
</View>
<StyledText style={styles.text}> Create poll </StyledText>
</>
)}
</Pressable>
{/* )} */}
{/* --------------------------------------------------------------------------- */}
{/* LOCATION */}
{/* --------------------------------------------------------------------------- */}
<Pressable
onPress={() => {
modal.close()
// AppConfig.isTablet?
NavigationRef.navigate("MessageLocationModal", {
onSend: (coordinate) => onLocationSelect(coordinate),
})
// : modal.open({
// background: "pattern",
// footer: "rgb",
// component: (
// <MessageLocationModal
// // onSend={(coordinate) => onLocationSelect(coordinate)}
// />
// ),
// })
}}
style={({ pressed }) => [
pressed
? { backgroundColor: AppColors.backgroundDark }
: { backgroundColor: "white" },
styles.itemWrapper,
]}
>
{({ pressed }) => (
<>
<View
style={[
pressed
? { backgroundColor: AppColors.primary }
: { backgroundColor: AppColors.backgroundLight },
styles.iconWrapper,
]}
>
<Icon
name="fal fa-location-dot"
size={20}
fill={pressed ? "white" : AppColors.iconDefault}
/>
</View>
<StyledText style={styles.text}> Location</StyledText>
</>
)}
</Pressable>
</>
)}
{/* --------------------------------------------------------------------------- */}
{/* SHARE PROFILE */}
{/* --------------------------------------------------------------------------- */}
<Pressable
onPress={() => {
modal.close()
NavigationRef.navigate("MessageInputProfileModal", {
onSend: (users) => onProfileSelect(users),
})
}}
style={({ pressed }) => [
pressed
? { backgroundColor: AppColors.backgroundDark }
: { backgroundColor: "white" },
styles.itemWrapper,
]}
>
{({ pressed }) => (
<>
<View
style={[
pressed
? { backgroundColor: AppColors.primary }
: { backgroundColor: AppColors.backgroundLight },
styles.iconWrapper,
]}
>
<Icon
name="fal fa-share-nodes"
size={20}
fill={pressed ? "white" : AppColors.iconDefault}
/>
</View>
<StyledText style={styles.text}>Share profile</StyledText>
</>
)}
</Pressable>
</View>
) } Adding a loading indicator while photos and videos are being loaded in onGallerySelect function
To add a loading indicator while photos and videos are being loaded in the onGallerySelect function of your MessageInputPopup component, you need to manage a loading state and use ActivityIndicator from React Native to display it. Here's how you can implement it step by step:
Import ActivityIndicator: Import the ActivityIndicator component from React Native.
Add Loading State: Use the useState hook to create a loading state variable to keep track of whether the media files are being loaded.
Update Loading State in onGallerySelect: Set the loading state to true when starting the photo/video loading process and back to false when the process completes.
Display ActivityIndicator: Conditionally render the ActivityIndicator while the loading state is true.
Here's how you can modify your component:
import React, { useState } from "react";
import { View, Pressable, ActivityIndicator } from "react-native";
import { launchImageLibrary } from "react-native-image-picker";
import { useLogger, useModal } from "@openchat/ui";
import { AppColors } from "../../../app/app-colors";
import { useStyles } from "./message-input-popup.style";
import { Icon } from "../../../ui-components/icon/icon.component";
import { StyledText } from "../../../ui-components/styled-text/styled-text";
import { AttachmentKindEnum, FileType } from "@openchat/types";
import { CryptoUtils } from "@openchat/framework";
// ... other imports
export function MessageInputPopup({
roomId,
onFilesSelected,
isShowFileAndProfile = false,
newMessagePacks,
// ... other props
}) {
// State variables
const [loading, setLoading] = useState(false);
const [files, setFiles] = useState<FileType[]>([]);
const logger = useLogger("MessageInputPopup");
const modal = useModal();
const styles = useStyles();
async function onGallerySelect() {
setLoading(true); // Start loading
const files = await launchImageLibrary({
mediaType: "mixed",
includeBase64: true,
includeExtra: true,
selectionLimit: 0,
});
if (!files.assets) {
setLoading(false); // Stop loading on early return
return;
}
const media: FileType[] = [];
for (let selectedFile of files.assets) {
if (!selectedFile.uri) continue;
const blob = await fetch(selectedFile.uri).then((response) => {
return response.blob();
});
const file = await new Promise<FileType>((ok, fail) => {
const reader = new FileReader();
reader.onload = () => {
const dataUrl = reader.result as string;
const file: FileType = {
id: CryptoUtils.sha256(dataUrl),
name: selectedFile.fileName ? selectedFile.fileName : "",
size: blob.size,
mimeType: blob.type,
data: dataUrl,
duration: null,
};
ok(file);
};
reader.onerror = fail;
reader.readAsDataURL(blob);
});
media.push(file);
}
setLoading(false); // Stop loading after processing completed
onFilesSelected(media, AttachmentKindEnum.media);
}
return (
<View style={styles.inputPopupContainer}>
{loading ? (
<ActivityIndicator size="large" color={AppColors.primary} />
) : (
<>
{isShowFileAndProfile && (
<Pressable
onPress={() => {
modal.close();
onGallerySelect();
}}
style={({ pressed }) => [
pressed
? { backgroundColor: AppColors.backgroundDark }
: { backgroundColor: "white" },
styles.itemWrapper,
]}
>
{({ pressed }) => (
<>
<View
style={[
pressed
? { backgroundColor: AppColors.primary }
: { backgroundColor: AppColors.backgroundLight },
styles.iconWrapper,
]}
>
<Icon
name="fal fa-photo-film"
size={20}
fill={pressed ? "white" : AppColors.iconDefault}
/>
</View>
<StyledText style={styles.text}>Image & Video</StyledText>
</>
)}
</Pressable>
)}
{/* Other code for buttons and options */}
</>
)}
</View>
);
}
loading State: Managed using the useState hook. It tracks whether the gallery selection process is currently loading.ActivityIndicator: Displays a spinner while loading is true, indicating to the user that a process is ongoing.ActivityIndicator is rendered when loading is true, and other UI components are rendered when loading is false.Not yet included in a published release.