Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
React: useState array doesn't change when state change method called

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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);
  }
};
about 4 years ago · Juan Pablo Isaza Relatório

0

Firstly, you should never mutate useState's state directly, use them as immutable entities. If you want to use it as initial value, clone it before:

const arr = [...arrayOfDocuments]
// or
const arr = arrayOfDocuments.slice()

Secondly, you are passing the same state array to the setter, then the state will not be updated. Cloning the state will solve this second point.

Finally, the best way to construct a new state from the old value is using a function:

setState(oldValue => (/* construct new state based on old value */))

this will avoid using a value that is not up to date. At the end, you will have:

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;
      }
    )
  }
};
about 4 years ago · Juan Pablo Isaza Relatório

0

I add a similar problem, and I solved by

instead of

const arr = arrayOfDocuments

try spreading the initial array

const arr = [...arrayOfDocuments]

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda