Home > Net >  React: useState array doesn't change when state change method called
React: useState array doesn't change when state change method called

Time:09-30

Array state doesn't change when state change method is beign called :

const [arrayOfDocuments, setArrayOfDocuments] = useState([]);

i tried : setArrayOfDocuments(...[]); or setArrayOfDocuments([]);

where i use my method :

  const pushToArrayOfDocuments = (obj) => {
    const arr = arrayOfDocuments;
    if (obj.filename && obj.file && obj.expiredate && obj.doctype) {
      const index = arr.map((e) => e.filename).indexOf(obj.filename);
      if (index !== -1) {
        arr[index] = obj;
      } else {
        arr.push(obj);
      }
      setArrayOfDocuments(arr);
    }
  };

Maybe the problem is push? and i should do setArrayOfDocuments(...arr); or setArrayOfDocuments(prev => [...prev,...arr]) but if doing so i guess it will go in infinte rendering as i'm passing pushToArrayOfDocuments to the subcomponents. Like this :

OperatorDocument
                  key={`Durc${count}`}
                  title="Durc"
                  description="Descrizione Durc"
                  setDocument={pushToArrayOfDocuments}
                  document={getObjectByName('Durc')}
                  filedocname="Durc"
                />

edit : doing like this : setArrayOfDocuments([...arr]); i get 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. Any help is appreciated.

CodePudding user response:

I add a similar problem, and I solved by

instead of

const arr = arrayOfDocuments

try spreading the initial array

const arr = [...arrayOfDocuments]

CodePudding user response:

You need to clone your array before adding it to state.

const arr = arrayOfDocuments.slice();

Full snippet:

const pushToArrayOfDocuments = (obj) => {
  if (obj.filename && obj.file && obj.expiredate && obj.doctype) {
    const arr = arrayOfDocuments.slice();
    const index = arr.findIndex(({ filename }) => filename === obj.filename);

    if (index > -1) {
      arr[index] = obj;
    } else {
      arr.push(obj);
    }

    setArrayOfDocuments(arr);
  }
};
  • Related