Home > database >  How to push into array and setState for multiple properties in a loop
How to push into array and setState for multiple properties in a loop

Time:11-18

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

CodePudding user response:

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

CodePudding user response:

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

  • Related