skip to Main Content

I have a problem in react js. I create empty Array of useState like this code :

const [fileUploadName, setUploadFileName] = useState([])

I want push my my file atteched name into this array ,
this is my code :

const InputFileHandler = event => {
file = event.target.files[0];
setUploadFileName(oldNames => [...oldNames, file.name])
const AllfileNames= fileUploadName 
}

When I push data into array at first time ,AllfileNames is ‘[]’, but when I push data at second time AllfileNames is the name of first attached name for example:

firstAttachName = 'download.jpg';
secondAttachName = 'download1.jpg';

In first push, AllfileNames give me this data: []
In second push, AllfileNames give me this data: ['download.jpg']

What is the problem with this code?

2

Answers


  1. useState hook in React is async. You need yo use useEffect with fileUploadName as dependency, and use this code const AllfileNames= fileUploadName inside it

    Login or Signup to reply.
  2. In your case the InputFileHandler is a callback that has a stale version of the set state function. My suggestion create a useCallback that takes in the event and instead of spreading the state from setState maybe try using the original state so spread state and append the new state at the end

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search