Home > Blockchain >  How can I updating setstate for object in ReactJS
How can I updating setstate for object in ReactJS

Time:11-09

I have two objects: first state

[{ "orders": [{ "id": "1587881", "uid": "237603" }, { "id": "1587880", "uid": "237603" }] }]

and add new data

[{ "orders": [{ "id": "1587879", "uid": "237603" }, { "id": "1587878", "uid": "237603" }] }]

i need get new state

[{ "orders": [{ "id": "1587881", "uid": "237603" }, { "id": "1587880", "uid": "237603" }, { "id": "1587879", "uid": "237603" }, { "id": "1587878", "uid": "237603" }] }]

Pleas help me!

I try it

import React, { Component } from 'react';

class Orders extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [{ "orders": [{ "id": "1587881", "uid": "237603" }, { "id": "1587880", "uid": "237603" }] }]
    };
  }

  loadingData = () => {
    const add = [{ "orders": [{ "id": "1587879", "uid": "237603" }, { "id": "1587878", "uid": "237603" }] }];
    this.setState({ data: [...this.state.data, ...add] });
  }

  componentDidMount() {
    this.loadingData();
  }

  render() {

    console.log(this.state.data);


    return (
      <div className="page" >
      </div>
    );
  }
}

export default Orders;

But I am not getting a single array of data ... two separate arrays are created. How can I fix this?

P.S. I am receiving data in this format and I cannot fix the format of the object.

CodePudding user response:

You are saying that the state data is an array of objects, this response is assuming that you will add orders to the same first index on that array.

loadingData = () => {
    const add = [{ "orders": [{ "id": "1587879", "uid": "237603" }, { "id": "1587878", "uid": "237603" }] }];
    this.setState(oldState => {
      const newData = { ...oldState.data };
      add[0].orders.forEach(x => newData[0].orders.push(x));
      return { data: newData };
    });
  }

CodePudding user response:

Here a working example: https://codesandbox.io/s/elated-lederberg-i3rtb?file=/src/App.js

You can do destructering on the first element of the array and then rebuild the way you want.

  const array1 = [
{
  orders: [
    { id: "1587881", uid: "237603" },
    { id: "1587880", uid: "237603" }
  ]
}
];
const array2 = [
{
  orders: [
    { id: "1587879", uid: "237603" },
    { id: "1587878", uid: "237603" }
  ]
}
];

const [firstEl] = array1;
const [secondEl] = array2;
console.log([{ orders: { ...firstEl.orders, ...secondEl.orders } 
}]);
  • Related