Home > Mobile >  How to insert data in array in react js?
How to insert data in array in react js?

Time:08-09

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.

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]]}
]

CodePudding user response:

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 });
};

Clarifications: setState is not reflecting changes to the state object immediatelly, in each iteration of map function state.dayDetails was an empty array, so ...this.state.dayDetails was always [], and thats why only last value was set there.

  • Related