Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!