Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot change state of Array due to "Order and size of this array must remain constant" Error

Whenever I upload a new set of files React throws the following error:

Warning: The final argument passed to useEffect changed size between
renders. The order and size of this array must remain constant.
Previous: [] Incoming: [[object Object]]

Here is the code I am using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default function Files({ onChange }) {
    // Step #1: initially `files` is an empty Array
    const [files, setFiles] = useState([])

    useEffect(() => {
      // step #3: Notify the parent of the change
      // `files` could be empty or not at this pointt
      onChange(files)
    }, files)

    async function onFilesChange() {
      let newFiles = await getNewFiles(...arguments)
      
      // Step #2: Now `files` becomes a populated Array of any give size
      setFiles(newFiles)

      // setState is async so I cannot notify the parent 
      // of the change right away by calling onChange() below:
        
      // onChange(newFiles)

      // I need to rely on useEffect() instead (see step #3)
    }

    function onFilesRemoved() {
      // empty the `files` array and notify parent via `useEffect()`
      setFiles([])
    }

    return (
      <>
        <input type="file" multiple onChange={onFilesChange}/>
        <button onClick={onFilesRemoved}>remove files</button>
      </>
    )
}

The error doesn’t make sense to me. The size of the array will necessarily vary from one upload to the next or if the user selects to remove all files.

>Solution :

The second parameter of the useEffect hook must be an array of dependencies.

Replace fileswith [files]and it should work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading