I'm getting this error :
Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
I have this state :
const [arrayOfDocuments, setArrayOfDocuments] = useState([]);
which store objects of type document
Function which add the docs to the state :
const pushToArrayOfDocuments = (obj) => {
if (obj.filename && obj.file && obj.expiredate && obj.doctype) {
setArrayOfDocuments((oldArr) => {
const arr = oldArr.slice();
const index = arr.map((e) => e.filename).indexOf(obj.filename);
if (index !== -1) {
arr[index] = obj;
} else {
arr.push(obj);
}
return arr;
});
}
};
Now this function is beign passed to the sub components :
like this :
<OperatorDocument
key={`Visura camerale${count}`}
title="Visura camerale"
setDocument={pushToArrayOfDocuments}
description=" in dolor."
document={getObjectByName('Visura camerale')}
filedocname="Visura camerale"
/>
Now inside the subcomponent i have this state :
const [file, setFile] = useState(document);
Now if this state changes i call setDocument inside useEffect
useEffect(() => {
setDocument(file);
}, [file, setDocument]);
and now i get the error. Any idea on how can i prevent this?
The error already told you the problem because setState is in the array dependency the component updates Everytime.
Try this Delete the setDocument and leave just file in the dependency array that way it updates only when the file changes
Like this [file]