reactjssetstate

React setState of the last object in the array state


i have array of objects state that hold users objects, when user clicks add button it adds a new empty object to the state

setUsers([...users, newRow]);

when user upload image i want to add the image file to that object:

<input type="file" accept="image/*" onChange={(e) => setUsers([...users, lastObject.image:e.target.files[0]])} />

how to get the image property of the last object in the state and set it ?


Solution

  • import React, { useState } from 'react';  
        
    const App = () => {  
        const [users, setUsers] = useState([]);  
        const handleUser = () => {  
            setUsers([...users, {}]);
        };  
        
        const handleImageUpload = (e) => {  
            const file = e.target.files[0];
            if (!file) return;
        
            const newUsers = [...users];
            newUsers[newUsers.length - 1] = {
                ...newUsers[newUsers.length - 1],
                image: file,           
          };  
        return (  
            <div>  
              <button onClick={handleUser}>Add User</button>  
              <input type="file" accept="image/*" onChange={handleImageUpload} />
            </div>  
        );  
    };  
        
    export default App;  
    

    Please try with this. Hope you any help. Thanks.