In React (Next.js), the act of replacing a file is performed instead of adding a file

I kindly request a review of my code prior to making any changes.

const test = () => {

const [files, setFiles] = useState ([]);

//I believe I need to modify the following statement.

const handleFile = (e) => {
   const newFiles = []
   for (let i=0; i < e.target.files.length; i++) {
       newFiles.push(e.target.files[i])
    }
        setFiles(newFiles)
};

return (

   {files.map((file, index) => (
     <div>
       <div key={index}>
         <p>
         {file.name}
         </p>
         <Button size='small' onClick={() => {deleteSelectedFile(file.name)}}>
         Delete
         </Button>
       </div>
     </div>
    ))}

    <div>
        <label onChange={handleFile}>
            <input type='file' multiple />+ Attach File
        </label>
    </div>

)

}

by using the handleFile function, I am able to successfully retrieve the files.

However, if I upload one file and then another file separately,

the second file replaces the first instead of being added alongside it.

No issues arise when uploading multiple files at once.

For example, after uploading 'hello.jpg', it displays correctly on the screen. Then, upon uploading 'goodbye.jpg', it shows up as expected, but it replaces 'hello.jpg'.

Thus, only 'goodbye.jpg' is displayed with a button, not

'hello.jpg' with a button
'goodbye.jpg' with a button

.

My objective is to have the files accumulate without overwriting each other.

Your insights would be greatly appreciated!

Answer №1

From my perspective, the key is to distribute the previous state values and the data within the files when the event changes.

import { useState } from "react";

export default function App() {
  const [files, setFiles] = useState([]);

  const handleChange = (e) => {
    // Necessary action to take
    setFiles((prev) => [...prev, ...Object.values(e.target.files)]);
  };

  return (
    <div>
      <label onChange={handleChange}>
        <input type="file" multiple />
      </label>
      {files.map((file) => {
        return <p>{file.name}</p>;
      })}
    </div>
  );
}

Answer №2

Instead of creating a new variable for new files, why not simply update the state for the existing files since it's already an array.

setFiles(existingFiles => [...existingFiles, e.target.files[i]]);

If feasible, please share a codepen link for further clarification.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...

Ending or stopping based on data retrieved from an ajax call

Currently, I have a php script that includes an image which, upon clicking, redirects the user to a different page. Additionally, there is an ajax/jQuery function in place to check if the user is logged in or not. When the user clicks on the link, the aja ...

I would like the capability to choose a roster of gods depending on a character's class and moral orientation

I am in the process of developing a character sheet for Dungeons & Dragons, and I'm looking to pass the values from two drop-down menus into a query that will then populate another select list. Despite trying various methods to retrieve the data, I ke ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

What is a dynamic route that does not include a slash?

I currently have a Next.js application set up with an SSR component that includes routes like /product1232312321. Previously, my solution was to create two folders: one named product and another nested folder inside it called [id]. Then I would redirect f ...

Bringing in the node-spotify or spotify-web modules to the browser for seamless integration

Has anyone successfully used Spotify's Playlist API in a browser? It seems that the web API only covers metadata, and to access the full API I need to use libspotify. Do I need to set up a Spotify API server myself or use node libraries like node-spot ...

When the user clicks on the login text field or password field, any existing text will

Currently, I am working on the login section of my website and I would like to implement a similar effect to Twitter's login form, where the Username and Password values disappear when the Textfield and Password field are in focus. I have attempted to ...

Issues with ng-repeat causing the Angular Editable table to malfunction

<table class="table table-bordered"> <tbody> <tr ng-repeat="playerOrTeam in template.editableTable track by $index"> <td style="text-align: center;" ng-repeat="playerOrTeamCat in playerOrTeam track by $index"> ...

Extracting information from a string with JSON in Javascript

Can you assist me? I have developed a web service that provides a clean string after clicking on the URL: { "PersonID": 125, "Title": "Security Officer", "Company": "TSA", "CellNum": "423-915-3224", "EmergencyPhone": "", "Email": " ...

Waiting for the code to execute once the filtering process is completed in Next.js using Javascript

I'm seeking a way to ensure that my code waits for the completion of my filter function before proceeding. The issue arises because my filter function, which incorporates another function called useLocalCompare, causes a delay in execution. This delay ...

What causes errors when installing create next app with postcss?

Having trouble with the code in question? It's quite simple. There is an "app" folder containing a server directory inside. With a terminal open, I navigate to the app directory by using cd command. Then, I run the command npx create-next-app client w ...

Creating a personalized pivot-table using the WebDataRock Javascript library with a unique configuration based on a

I'm having trouble getting this demo to work with the "hierarchy" parameter. Even when I specify the parameter value, it seems to apply the condition to the entire hierarchy chain. "conditions": [{ "formula": "#val ...

Dispatching an asynchronous function error in React with TypeScript and Redux - the parameter type is not assignable to AnyAction

Currently, I am in the process of developing a web application that utilizes Firebase as its database, along with Redux and TypeScript for state management. Within my code, I have a dispatch function nested inside a callback function like so: export const ...

Validation of nested phone numbers using jQuery

I'm trying to figure out how to incorporate the jQuery validation plug-in into a multi-step form where validation occurs on each step as the user progresses. I know that typically, the validation plug-in is triggered by a submit request, but in this c ...

Storing JSON data using Vuex

As I am delving into the world of Vuex store used with vue.js, I find myself wanting to implement it in a specific scenario. 1. Is STATE referring to any data, whether static or dynamic, that is provided by the server or stored in a JSON format? TEMPLATE ...

Increase division height when mouse hovers over it

I want the height of the div to be 50px by default and change to 300px onmouseover. I have implemented this as follows: <style type="text/css"> #div1{ height:50px; overflow:hidden; } #div1:hover{ height:300px; } </style> <body> <div i ...

Leveraging the power of Prisma alongside the latest version of Yarn

My current project involves building an app using Next.js, Next-Auth, and Prisma, with API Routes for backend code. Recently, I updated Yarn on my computer to version v3.1.1. Following this update, I created a .yarnrc.yml file where I specified the nodeLin ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

Validation of forms on the client side using Angular in a Rails application

I'm facing an issue with implementing client-side validations for a devise registration form using Angular. Although I am able to add the "invalid" class to the fields as expected, I am struggling to get any output when using ng-show. There are no oth ...

Generate a new array using a single value extracted from an existing array

I'm new to working with arrays. Before this, I used to manually code everything in HTML. My question is, can you create an array based on the values of another array? var pmmain =["aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", ...