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

195
Vistas
How to push into array and setState for multiple properties in a loop

I want to set multiple array while inserting items into the array Can anybody suggest me whats wrong with the code.

import React from "react";
import { render } from "react-dom";

class App extends React.Component {
  constructor() {
    super();
    this.state = { aArr: [], bArr: [], cArr: [] };
    this.someFunction();
  }

  someFunction() {
    let result = [
      { a: 1, b: 2, c: 3 },
      { a: 4, b: 5, c: 6 }
    ];
    result.forEach((item) => {
      this.setState({
        aArr: [...this.state.aArr, item.a],
        bArr: [...this.state.bArr, item.b],
        cArr: [...this.state.cArr, item.c]
      });
    });
  }
  render() {
    return (
      <div>
        aArr: {this.state.aArr}
        bArr: {this.state.bArr}
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

final output should be aArr : 1,4 bArr : 2,5

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You are trying to set state in a forEach loop. Yet this.setState() is async and takes some time to execute. So you are not able to set data in the state. You need to update your result in some other variable then you can set that data in your state. Here's how you can do it-


class App extends React.Component {

  constructor() {
    super();

    this.state = { aArr: [], bArr: [], cArr: [] };

    let result = [
        { a: 1, b: 2, c: 3 },
        { a: 4, b: 5, c: 6 }
    ];

    const {aArr, bArr, cArr} = this.state

    result.map(res => {
        aArr.push(res.a)
        bArr.push(res.b)
        cArr.push(res.c)
    })

    this.setState({aArr, bArr, cArr});

  } 
  render() {
    return <div>aArr: {this.state.aArr.join(', ')} <br/>
    bArr: {this.state.bArr.join(', ')}</div>;
  }
}

You can find the working code here

about 4 years ago · Juan Pablo Isaza Denunciar

0

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

https://reactjs.org/docs/hooks-reference.html#usereducer

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