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:
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.
CodePudding user response:
The second parameter of the useEffect hook must be an array of dependencies.
Replace files
with [files]
and it should work.