Troubleshooting Problems with Uploading Images through a React-Based Web Browser Interface

I'm currently working on allowing users to upload multiple images using React and then saving them to a server.

One issue I've encountered is that sometimes when I click choose image, it works fine, but other times it does not. The same inconsistency happens with showing the images as well. Here is the code snippet I am using:

const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [selectedFiles, setSelectedFiles] = useState([]);
const [isSelected, setIsSelected] = useState(false);

const fileSelectedHandler = (event) => {
    console.log(event.target.files[0]);
    const files = selectedFiles;
    files.push(event.target.files[0]);
    setSelectedFiles(files);
    setIsSelected(true);
    console.log(selectedFiles);
}

const fileUploadHandler = () => {
    axios.post('http://')
}

return (
    <div className="container">
        <p>Please Enter Category name: </p>
        <TextField
            id="standard-multiline-flexible"
            label="Name"
            multiline
            rowsMax={4}
            variant="filled"
            color="secondary"
            value={name}
            onChange={(event) => setName(event.target.value)}
        />
        <p>Please Enter Category Description: </p>
        <TextField
            id="standard-multiline-flexible"
            label="Description"
            multiline
            rowsMax={4}
            variant="filled"
            color="secondary"
            value={description}
            onChange={(event) => setDescription(event.target.value)}
        />
        <input type="file" onChange={fileSelectedHandler}/>
        
        {
            selectedFiles.length > 0 ?
            
                <div className="row">
                    {
                        selectedFiles.map((file, index) => {
                                console.log(file, index);
                                return (
                                    <div className="column">
                                        <img className="added_images" width="100%" src={URL.createObjectURL(file)} thumbnail />
                                    </div>
                                )
                        })
                    }
                </div>
            :
                null
        }
    </div>
)

and here is my CSS styling:

 * {
    box-sizing: border-box;
}

.container {
    display: flex;
    flex-direction: column;
}

.column {
    float: left;
    width: 33.33%;
    height: 200px;
    padding: 5px;
}
  
/* Clear floats after image containers */
.row::after {
    content: "";
    display: table;
    clear: both;
}

During debugging, I noticed that the selectedFiles hook does contain all the uploaded files. However, the problem lies in it not triggering the render consistently. Why could this be happening?

Answer №1

One common issue is when you assign the entire selectedFiles array to another variable files like this:

const files = selectedFiles;

This action will create a reference of selectedFiles in the files constant. Therefore, if you add new values to one array and then try to update the other with the same values, React won't trigger a re-render.

To resolve this problem, it's recommended to shallow copy the array using either of the following methods:

const files = [...selectedFiles];

Or when updating the array, use spread operators as shown below:

setSelectedFiles([...files]);

Alternatively, you can directly update your array state without creating a new variable like this:


const fileSelectedHandler = (event) => {
    setSelectedFiles(prevSelected => [...prevSelected, event.target.files[0]]);
}

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

What is the most straightforward method to convert a current Express node app into a static site?

After primarily working with React and create-react-app, I've grown accustomed to the convenience of having a build utility for npm that simplifies deploying projects to static web hosting platforms like github pages or surge. This process ultimately ...

The proper method for developing Vue components that are dependent on the parent build tools

In my experience, this issue might also arise in other frameworks with plugin/component ecosystems that rely on specific build tools (such as React components with JSX). While Vue serves as my use-case. Having developed numerous Vue components as single . ...

JavaScript array with more than 4 elements

I am working on a program where I have created an array and now want to display all the words that contain more than 4 letters. Check out my code snippet below: function oppC(){ var ord = ["Apple", "Two", "Yesterday", "mother", "lol", "car", "co ...

What is the best place to house API requests in a React / Next.js application?

In our project, we utilize redux-thunk alongside redux. However, there are instances where shared business logic cannot utilize redux. This is particularly true for code used within Wordpress plugins in shortcodes where redux cannot be implemented. So whe ...

Changing div height based on the height of another dynamic div

Looking to create a box that matches the height of the entire page, live height minus another dynamic div called #wrapping. I have code that offsets it instead of removing the height of the div... function adjustBoxHeight() { var viewPortHeight = $(wind ...

How to validate a <select> element with parsley.js when it is dynamically populated with an object?

I'm struggling to validate a <select> element in my form. With the help of knockout.js, I select a location which then populates the Service Point based on the Location chosen. However, when I try to validate the form using parsley.js after pres ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

What is the process for adjusting the expiration time of a GitLab accessToken?

I am currently using NextAuth for logging in with GitLab, but I am encountering an issue where my accessToken changes every 2 hours. How can I ensure that it remains valid for a longer period so that I can successfully store it in my database? It's wo ...

Issue with creating a new jstree node

I recently put together a basic jstree. When I click on a link, it triggers the createNode() function. This function utilizes the create feature from the API to generate a new node. It appears to be a common issue with jQuery that I am encountering. Any ...

Retrieving data from a remote source repeatedly based on user selections on a single page

In my current project, I am utilizing next js to build a web application. One of the pages in this app has the following structure: <page> <component_1> This component fetches data from a remote server using `getInitialProps` (alternat ...

I’m having trouble identifying the error. Is there a possible infinite loop happening somewhere?

// JavaScript Document var person = prompt("ENTER INPUT", ""); var count = 0; var array = person.split(","); var freq = []; var words = []; // Commented lines removed for simplicity var i = 0, j = 0; while (array.length > 0) { var temp = array ...

Steps for converting a window to a PDF file rather than an XPS file

Whenever I attempt to print the contents of my HTML page using window.print(), it always creates an XPS file. However, what I really need is for it to generate a PDF file instead. Any assistance would be greatly appreciated. Thank you! ...

What is the best way to submit a form using PHP to send an email, implement Ajax for seamless transitions, and display a message next to the form without any screen refresh?

Upon clicking the submit button, I am looking to achieve two things: (1) Sending the form data via email using PHP without refreshing the page. (2) Displaying a thank you message next to the form utilizing Ajax. Most of the functionality is in pl ...

Passing the value of each table row using Ajax

On my webpage, I have a list of orders displayed. I'm facing an issue where the value of each row in the table is not being passed correctly to my controller and database when a user clicks on a button - it always shows null. Can someone please assist ...

Tips on how to incorporate a .js file into my .tsx file

I ran into an issue with webpack displaying the following message: ERROR in ./app/app.tsx (4,25): error TS2307: Cannot find module './sample-data'. The imports in my code are as follows: import * as React from 'react'; import * ...

I'm struggling to make this script replace the values within the table

I am struggling with a script that I want to use for replacing values in a google doc template with data from a google sheet. The script is able to recognize the variables and generate unique file names based on the information from the google sheet. Howev ...

Issue with setting a cookie on a separate domain using Express and React

My backend is hosted on a server, such as backend.vercel.app, and my frontend is on another server, like frontend.vercel.app. When a user makes a request to the /login route, I set the cookie using the following code: const setCookie = (req, res, token) = ...

Submit a single data value to two separate models in JSON format using MongoDB

I recently developed a code with 2 essential functions: module.exports.registerAccount = (reqBody) => { let newAccount = new User({ firstName : reqBody.firstName, lastName : reqBody.lastName, email : reqBody.email, mobileNum : reqBody.m ...

An error message has been detected, stating that the action of navigating with a payload was not properly handled

I'm encountering an issue with the "onLogin" function in the "LoginComponent". When I tap on the TouchableOpacity linked to that function, my intention is for the user to be directed to the "HomeComponent". However, instead of achieving this, I receiv ...

Show the screen name of a user upon disconnecting from the server

When a user disconnects from the server, I want to display a message. Currently, the message is shown to all users, but I'm having trouble displaying the actual user's name. Instead, it shows the name of the connected clients to themselves. I&apo ...