Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda