React, my setProgess didn't work const storeLargeFileAtFront = async (e) => {…
- User
React, my setProgess didn't work const storeLargeFileAtFront = async (e) => { e.preventDefault(); if (!file) return;
setLoading(true); setError(null); setProgress(0); // Reset progress when a new file is selected const reader = new FileReader(); // Wait until the file is fully loaded reader.onload = async (event) => { const fileContent = event.target.result; // Get file content from reader const rows = fileContent.split(/\r?\n/); // Split the file content into rows (handles both Windows and Unix line endings) // const totalChunks = Math.ceil(rows.length / CHUNK_SIZE); // Total number of chunks based on row count const CHUNK_ROW_SIZE = 2000; const totalChunks = Math.ceil(rows.length / CHUNK_ROW_SIZE); let allParsedData = []; // To store parsed data from all chunks const header = rows[0]; // Extract the header (first row) const headerRow = header.split(","); // Split header into columns (assuming CSV format) // Function to process each chunk const processChunk = async (startRow, endRow, chunkIndex) => { let chunkRows = rows.slice(startRow, endRow); // Get the rows for this chunk if (chunkIndex !== 0) { // Add header to the chunk (skip adding header for the first chunk) chunkRows.unshift(header); } return new Promise((resolve, reject) => { // Convert rows back into CSV format string const chunkCSV = chunkRows.join("\n"); // Parse the chunk using PapaParse Papa.parse(chunkCSV, { complete: (result) => { // console.log(`Chunk ${chunkIndex}:`, result.data); allParsedData.push(...result.data); // Append parsed data more efficiently resolve(); }, error: (err) => { reject(err); }, header: true, // If the first row contains headers skipEmptyLines: true, // Skip empty lines dynamicTyping: true, // Automatically convert data types (e.g., strings to numbers) }); }); }; try { // Process each chunk sequentially for (let i = 0; i < totalChunks; i++) { const startRow = i * CHUNK_ROW_SIZE; const endRow = Math.min((i + 1) * CHUNK_ROW_SIZE, rows.length); await processChunk(startRow, endRow, i); const progressNumber = ((i + 1) / totalChunks) * 100 setProgress(progressNumber); // Update progress } setProgress(100); // After all chunks are processed, calculate the number of rows, columns, and the head of the data const numRows = allParsedData.length; // Total number of rows const columns = allParsedData[0] ? Object.keys(allParsedData[0]) : []; // Columns from the first row const headData = allParsedData.slice(0, 5); // Get the first 5 rows as the 'head' of the data // Get file creation time and format it for display const lastModified = file.lastModified; const lastModifiedDate = new Date(lastModified); // Convert to Date object const formattedDate = lastModifiedDate.toLocaleString(); // Format as a string // Prepare file info to be set in state and passed to parent component const fileInfoAtFront = { length: numRows, columns: columns, head_of_data: headData, creation_time: formattedDate, df_dict: allParsedData, // Store parsed data here }; // Set the file info in state setFileInfo(fileInfoAtFront); // Pass the same data to the parent component (onDataUpload) onDataUpload(fileInfoAtFront); // Turn off loading spinner setLoading(false); } catch (err) { setError('Error processing file chunk'); setLoading(false); } }; // Handle any error during file reading reader.onerror = (err) => { setError('Error reading the file.'); setLoading(false); }; // Start reading the file as text reader.readAsText(file); }; {/* Loading Progress Bar */} {loading && ( <Box sx={{ width: '100%', marginTop: 2 }}> <Typography variant="body1" color="textSecondary" sx={{ marginBottom: 1 }}> Parsing CSV... {Math.round(progress)}% </Typography> <LinearProgress variant="determinate" value={progress} sx={{ height: 8, // Adjust height for the progress bar borderRadius: 4, // Rounded corners backgroundColor: '#e0e0e0', // Light gray background for the progress bar '& .MuiLinearProgress-bar': { backgroundColor: '#4caf50', // Green color for the progress }, }} /> </Box> )} - Assistant