import { FileType } from "@openchat/types" import { useEffect, useRef, useState } from…
- User
import { FileType } from "@openchat/types" import { useEffect, useRef, useState } from "react" import { Image, LayoutAnimation, TouchableOpacity, View } from "react-native" import { FlatList } from "react-native-gesture-handler" import Video, { VideoRef } from "react-native-video" import RNFS from "react-native-fs" import { AppColors } from "../../../app/app.colors" import { Icon } from "../../../ui-components/icon/icon.component" import { StyledText } from "../../../ui-components/styled-text/styled-text" import { useStyles } from "./message-attachment-uploaded-files-preview.style"
export const MessageAttachmentUploadedFilesPreview = ({ files, onFileRemove, screen, isEnabled = false, }: { files: FileType[] onFileRemove: (fileId: string) => void screen?: string isEnabled?: boolean }) => { // ------------------------------------------------------------------------------------ // variables // ------------------------------------------------------------------------------------
const styles = useStyles() const videoRef = useRef(null) const flatListRef = useRef<FlatList>(null) const layoutAnimConfig = { duration: 300, update: { type: LayoutAnimation.Types.easeInEaseOut, }, delete: { duration: 100, type: LayoutAnimation.Types.easeInEaseOut, property: LayoutAnimation.Properties.opacity, }, } const [isDownloading, setIsDownloading] = useState(false) const [videoFilePath, setVideoFilePath] = useState<string | null>(null)
useEffect(() => { for (const file of files) { if (file.mimeType.startsWith("video")) { downloadVideo(file.data, "temp_video.mp4") } } }, [files])
// ------------------------------------------------------------------------------------ // functions // ------------------------------------------------------------------------------------ function formatSizeUnits(bytes: number) { let size if (bytes >= 1073741824) { size = (bytes / 1073741824).toFixed(2) + " GB" } else if (bytes >= 1048576) { size = (bytes / 1048576).toFixed(2) + " MB" } else if (bytes >= 1024) { size = (bytes / 1024).toFixed(2) + " KB" } else if (bytes > 1) { size = bytes + " bytes" } else if (bytes == 1) { size = bytes + " byte" } else { size = "0 byte" } return size }
async function downloadVideo(url: string, fileName: string) { setIsDownloading(true) const path =
${RNFS.DocumentDirectoryPath}/${fileName}const downloadOptions = { fromUrl: url, toFile: path, } try { await RNFS.downloadFile(downloadOptions).promise setVideoFilePath(path) setIsDownloading(false) } catch (error) { console.error("Error downloading video", error) setIsDownloading(false) } }// ------------------------------------------------------------------------------------ return ( <> <FlatList showsHorizontalScrollIndicator={false} ref={flatListRef} contentContainerStyle={[ styles.scrollWrapper, { gap: screen === "MessageBoardCardInfo" ? 5 : 10 }, ]} horizontal={true} scrollEnabled={isEnabled ? false : true} data={files} keyExtractor={(file) => file.id} renderItem={({ item: file }) => { return ( {file.mimeType.startsWith("image") && ( <Image resizeMode="cover" style={styles.media} source={{ uri: file.data }} /> )} {file.mimeType.startsWith("video") && videoFilePath && ( <Video ref={videoRef} resizeMode="cover" source={{ uri:
file://${videoFilePath}}} paused={true} controls={false} style={styles.videoPreview} pictureInPicture={true} /> )}{file.mimeType.startsWith("audio") && <></>} {!file.mimeType.startsWith("image") && !file.mimeType.startsWith("video") && !file.mimeType.startsWith("audio") && ( <View style={styles.anotherFiles}> <Icon name="fal fa-file-lines" bald={true} size={25} fill={AppColors.placeholderText} /> <View style={styles.fileInfoWrapper}> <StyledText ellipsizeMode="tail" numberOfLines={1} style={styles.fileName} > {file.name} </StyledText> <StyledText style={styles.fileSize}> {formatSizeUnits(file.size)} </StyledText> </View> </View> )} {screen !== "MessageBoardCardInfo" && ( <TouchableOpacity activeOpacity={0.9} style={styles.xHolder} onPress={() => { onFileRemove(file.id) LayoutAnimation.configureNext(layoutAnimConfig) }} > <Icon name="fal fa-xmark" bald={true} height={14} width={9} /> </TouchableOpacity> )} </View> ) }} /> </>) } I have issue when I try two upload more than one files like I try to upload 3 videos but it duplicates first videos three time. How to fix it if I upload three different videos they should uploaded ?
- Assistant
The problem you're encountering is related to how the state and side-effects in your component are being managed, particularly with downloading and setting up videos. It looks like the
useEffectis being triggered for each file including when a new file is added. This can sometimes cause race conditions or repeated setting of the video file path.Here are some steps to fix this issue:
-
Separate State Management for Each File Type: Track the download path for each file separately.
-
Controlled Side Effects: Ensure that each file's download and rendering are controlled independently.
Let's make these adjustments:
-
Update State Management:
- Replace the single
videoFilePathstate with a mapping of file IDs to their local paths.
- Replace the single
-
Separate Logic:
- Refactor the side-effect logic to ensure it works independently for each file and only acts upon necessary changes.
Here's a modified version of your component:
import { FileType } from "@openchat/types" import { useEffect, useRef, useState } from "react" import { Image, LayoutAnimation, TouchableOpacity, View } from "react-native" import { FlatList } from "react-native-gesture-handler" import Video, { VideoRef } from "react-native-video" import RNFS from "react-native-fs" import { AppColors } from "../../../app/app.colors" import { Icon } from "../../../ui-components/icon/icon.component" import { StyledText } from "../../../ui-components/styled-text/styled-text" import { useStyles } from "./message-attachment-uploaded-files-preview.style" export const MessageAttachmentUploadedFilesPreview = ({ files, onFileRemove, screen, isEnabled = false, }: { files: FileType[] onFileRemove: (fileId: string) => void screen?: string isEnabled?: boolean }) => { // ------------------------------------------------------------------------------------ // variables // ------------------------------------------------------------------------------------ const styles = useStyles() const videoRef = useRef<VideoRef>(null) const flatListRef = useRef<FlatList<FileType>>(null) const layoutAnimConfig = { duration: 300, update: { type: LayoutAnimation.Types.easeInEaseOut, }, delete: { duration: 100, type: LayoutAnimation.Types.easeInEaseOut, property: LayoutAnimation.Properties.opacity, }, } const [isDownloading, setIsDownloading] = useState(false) const [videoFilePaths, setVideoFilePaths] = useState<Record<string, string>>({}) useEffect(() => { files.forEach((file) => { if (file.mimeType.startsWith("video") && !videoFilePaths[file.id]) { downloadVideo(file.data, file.id) } }) }, [files]) // ------------------------------------------------------------------------------------ // functions // ------------------------------------------------------------------------------------ function formatSizeUnits(bytes: number) { let size if (bytes >= 1073741824) { size = (bytes / 1073741824).toFixed(2) + " GB" } else if (bytes >= 1048576) { size = (bytes / 1048576).toFixed(2) + " MB" } else if (bytes >= 1024) { size = (bytes / 1024).toFixed(2) + " KB" } else if (bytes > 1) { size = bytes + " bytes" } else if (bytes == 1) { size = bytes + " byte" } else { size = "0 byte" } return size } async function downloadVideo(url: string, fileId: string) { setIsDownloading(true) const path = `${RNFS.DocumentDirectoryPath}/${fileId}.mp4` const downloadOptions = { fromUrl: url, toFile: path, } try { await RNFS.downloadFile(downloadOptions).promise setVideoFilePaths((prevPaths) => ({ ...prevPaths, [fileId]: path })) setIsDownloading(false) } catch (error) { console.error("Error downloading video", error) setIsDownloading(false) } } // ------------------------------------------------------------------------------------ return ( <> <FlatList showsHorizontalScrollIndicator={false} ref={flatListRef} contentContainerStyle={[ styles.scrollWrapper, { gap: screen === "MessageBoardCardInfo" ? 5 : 10 }, ]} horizontal={true} scrollEnabled={isEnabled ? false : true} data={files} keyExtractor={(file) => file.id} renderItem={({ item: file }) => { return ( <View style={styles.attachmentItem} key={file.id}> {file.mimeType.startsWith("image") && ( <View> <Image resizeMode="cover" style={styles.media} source={{ uri: file.data }} /> </View> )} {file.mimeType.startsWith("video") && videoFilePaths[file.id] && ( <Video ref={videoRef} resizeMode="cover" source={{ uri: `file://${videoFilePaths[file.id]}` }} paused={true} controls={false} style={styles.videoPreview} pictureInPicture={true} /> )} {file.mimeType.startsWith("audio") && <></>} {!file.mimeType.startsWith("image") && !file.mimeType.startsWith("video") && !file.mimeType.startsWith("audio") && ( <View style={styles.anotherFiles}> <Icon name="fal fa-file-lines" bald={true} size={25} fill={AppColors.placeholderText} /> <View style={styles.fileInfoWrapper}> <StyledText ellipsizeMode="tail" numberOfLines={1} style={styles.fileName} > {file.name} </StyledText> <StyledText style={styles.fileSize}> {formatSizeUnits(file.size)} </StyledText> </View> </View> )} {screen !== "MessageBoardCardInfo" && ( <TouchableOpacity activeOpacity={0.9} style={styles.xHolder} onPress={() => { onFileRemove(file.id) LayoutAnimation.configureNext(layoutAnimConfig) setVideoFilePaths((prevPaths) => { const updatedPaths = { ...prevPaths } delete updatedPaths[file.id] return updatedPaths }) }} > <Icon name="fal fa-xmark" bald={true} height={14} width={9} /> </TouchableOpacity> )} </View> ) }} /> </> ) }Explanation:
-
State Update for Video Paths:
videoFilePathsnow stores paths to the downloaded files keyed by file ID.
-
Effect for Downloading Videos:
- The
useEffectchecks if thevideoFilePathsalready contains the downloaded path for a video file to avoid redundant downloads.
- The
-
Handle File Removal:
- When a file is removed, its path is also removed from
videoFilePaths.
- When a file is removed, its path is also removed from
This will ensure that each video file is downloaded and managed independently without duplicating the video paths.
-
- User
const [videoFilePaths, setVideoFilePaths] = useState<Record<string, string>>({}) please tell me about Record, why you are using it ?
- Assistant
Certainly! The
Recordutility type in TypeScript is a very useful type that allows you to create an object type with specific keys and value types. Here’s a detailed explanation of why and how it's used:What is
Record?The
Recordutility type is a TypeScript construct that helps define a type for an object where keys are of a certain type and values are of another type.Syntax
The syntax for
Recordis:Record<KeyType, ValueType>Example in Your Code
In the provided code, the state is defined as:
const [videoFilePaths, setVideoFilePaths] = useState<Record<string, string>>({})Here's what this means:
Record<string, string>: This means thatvideoFilePathsis an object where each key is astringand each value is also astring.{}: This initializesvideoFilePathsas an empty object.
Why use
Record?- Type Safety: When we use
Record<string, string>, we are explicitly stating thatvideoFilePathswill be an object with string keys and string values. This ensures type safety—a core principle of TypeScript. - Code Readability: It makes the code more readable and self-documenting. Any developer looking at this state definition can immediately understand what the state is supposed to represent.
- Type Checking: It helps the TypeScript compiler to catch errors during development. For instance, if you accidentally try to set a non-string key or value, TypeScript will throw a type error.
How
RecordBenefits Your ComponentIn this context,
Record<string, string>is particularly useful because:- Unique Identifiers for Files: Each video file has a unique ID (string). Using the file ID as a key ensures that you can uniquely identify and store the file paths.
- File Path Storage: The value associated with each key (file ID) is the file path, which is also a string. This allows you to efficiently map each video file's ID to its downloaded local path.
Example of Record Usage
Imagine you have a set of video files, each identified by a unique ID, and you want to keep a track of their downloaded paths. Here’s how
Recordmakes this easy:type VideoFileID = string; type FilePath = string; const videoPaths: Record<VideoFileID, FilePath> = { 'file-1': '/path/to/video1.mp4', 'file-2': '/path/to/video2.mp4', }; videoPaths['file-1']; // '/path/to/video1.mp4' videoPaths['file-3']; // Property 'file-3' does not exist on type 'Record<string, string>'Why Not Use a Simple Object Type?
You could technically use a plain object type:
const [videoFilePaths, setVideoFilePaths] = useState<{ [id: string]: string }>({})However,
Record<string, string>is often preferred because:- Clarity:
Recordtype is clearer and more idiomatic in TypeScript for such use-cases. - Consistency: It fits well with TypeScript's utility types and makes future type transformations easier.
In summary, using
Record<string, string>ensures your state management is type-safe, readable, and consistent. It makes it clear that keys are expected to be strings (video file IDs) and values are also strings (file paths), which is exactly what you need for managing downloaded video file paths.