user12562266
user12562266

Reputation:

How to push data to array ReactJs

Is it possible to push the Januarys , Februarys , Marchs, Aprils, ... in the render into an array called Revenues?

constructor(props) {
    super(props);
    this.state = {
      January:[],
      February:[],
      March:[],
      April:[],
      May:[],
      June:[],
      July:[],
      August:[],
      September:[],
      October:[],
      November:[],
      December:[],
      Type: "bar",
      Revenues:[],
   }

render It's the part where I want to put my valuable interpreter values ​​into the array.

 addMonthToRevenues = (Octobersss) => {
    this.setState({
      Revenues: [ ...this.state.Revenues, Octobersss]
    }) }

I want to put the calculated values under render and store it in an array called Revenues.

 render {
               const Octobersss =  Octobersss.reduce(( sum,{price, quantity}) =>  sum + price * quantity ,0);
               const Februarys =  February.reduce(( sum,{price, quantity}) =>  sum + price * quantity ,0);
               const Marchs =  March.reduce(( sum,{price, quantity}) =>  sum + price * quantity ,0);
               const Aprils =  April.reduce(( sum,{price, quantity}) =>  sum + price * quantity ,0);
               const Mays =  May.reduce(( sum,{price, quantity}) =>  sum + price * quantity ,0);
               const Junes =  June.reduce(( sum,{price, quantity}) =>  sum + price * quantity ,0);
               const Julys =  July.reduce(( sum,{price, quantity}) =>  sum + price * quantity ,0);
               const Augusts =  August.reduce(( sum,{price, quantity}) =>  sum + price * quantity ,0);
 }

DataChart

const data = {   labels: [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'],   datasets: [
    {
      label: 'รายรับ',
      fill: true,
      lineTension: 0.5,
      backgroundColor: 'green',
      borderColor: 'rgba(75,192,192,1)',
      borderCapStyle: 'butt',
      borderDash: [],
      borderDashOffset: 0.0,
      borderJoinStyle: 'miter',
      pointBorderColor: 'rgba(75,192,192,1)',
      pointBackgroundColor: '#fff',
      pointBorderWidth: 1,
      pointHoverRadius: 5,
      pointHoverBackgroundColor: 'rgba(75,192,192,1)',
      pointHoverBorderColor: 'rgba(220,220,220,1)',
      pointHoverBorderWidth: 2,
      pointRadius: 1,
      pointHitRadius: 10,
      data: this.state.Revenues
    },   ] };

Chart

<Bar
    data={data}
    width={60}
    height={30}
               />

Upvotes: 0

Views: 65

Answers (1)

knada
knada

Reputation: 344

You can get what you want with something like this

addMonthToRevenues = month => {
    this.setState(prevState => {
        Revenues: [...prevState.Revenues, month]
    })
}

Then call it for each month you want to add like

addMonthToRevenues(Januarys)

Upvotes: 1

Related Questions