Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert data in array in react js?

I’m using react.js and I have class base component.
Now the scenario is. I have one array with the name of partitions.

partitions=["P1","P2","P3"]

and I have another array with the name dayDetails which is null at the start.

When my components mounts. I map partitions array and add an object in dayDetail array. Number of elements in partition array will be the number of objects put in the dayDetail array.
Now the problem is only One object is putting in the dayDetail but it suppose to add three because number of partitions are 3.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

here is my code below.

import React from "react";

class Step2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        partitions:["P1","P2","P3"],
        dayDetails:[],

    };
  }


  componentDidMount() {
    this.setTimePriceNullJson()
  }

  setTimePriceNullJson = () => {
    {this.state.partitions.map((item,index)=>( 
       this.setState({dayDetails:[...this.state.dayDetails,
        {
          "partitionIndex":index,
          "timings":[
              {"name":"sunday"}
          ],
          "pricings":[
              {"name":"sunday"}
          ]
        }
        
      ]})
    )
    )}
    
  }

  componentDidUpdate(){
    console.log("--> ",this.state.dayDetails)

  }


  render() {
    return (
      <div style={styles.main_container}>
        ...
      </div>
    )
  }
}

export default Step2;

Right now output is coming:
this.state.dayDetail output is :

[{"partitionIndex": 2, "pricings": [[Object]], "timings": [[Object]]}]

Desire output is:

[
{"partitionIndex": 0, "pricings": [[Object]], "timings": [[Object]]},
{"partitionIndex": 1, "pricings": [[Object]], "timings": [[Object]]},
{"partitionIndex": 2, "pricings": [[Object]], "timings": [[Object]]}
]

>Solution :

Just do everything step by step. It will be much shorter and easier to read.

setTimePriceNullJson = () => {
  const dayDetails = this.state.partitions.map((x, i) => {
    return {
      partitionIndex: i,
      timings: [{ name: "sunday" }],
      pricings: [{ name: "sunday" }]
    };
  });
  this.setState({ ...this.state, dayDetails: dayDetails });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading