-1

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?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
abolfazl_mehdi
  • 179
  • 2
  • 12
  • 1
    Duplicate of [Why does calling react setState method not mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) – Guy Incognito Apr 09 '23 at 08:23

2 Answers2

2

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

Boris
  • 35
  • 4
  • use state is not async but the fact that sometimes states might be pushed during a render might make it seem async – Maix Apr 09 '23 at 08:44
  • Changing state in React is always async because it can result in an expensive operation. Making it synchronous might leave the browser unresponsive. – Boris Apr 09 '23 at 09:29
-1

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

Maix
  • 57
  • 1
  • 1