Calicorio2
Calicorio2

Reputation: 37

Can't access value from an array inside JSON object in Reactjs

I have this state defined:

 constructor(props){
        super(props);

        this.state = {
            open: false,
            customers:[],
            customer:{},
            products:[],
            product:{},
            orders:[],
            order:{},
            newForm:true,
            phoneNumbererror:null,
            shop:this.props.salon,
            value:'a',
            showTab:'none',
            slideIndex: 0,

        };
    }

With the following function which contains a fetch, I recieve an array of objects with responseData.

getHistory(){
        console.log("Log antes del fetch de customer id");
        console.log(this.state.customer._id);
        fetch(
            DOMAIN+'/api/orders/customer/'+this.state.customer._id, {
                method: 'get',
                dataType: 'json',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Authorization':'Bearer '+this.props.token
                }
            })
            .then((response) =>
            {
                return response.json();
            })
            .then((responseData) => {
                this.setState({orders:responseData})
                console.log("Log del responseData");
                console.log(responseData);

            })
            .catch(function() {
                console.log("error");
            });
    }

This function is called in handleCellClick, where I pass some data from the consumer, such as the ID:

handleCellClick(y,x,row){
        this.setState({
            open:true,
            slideIndex: 0,
            newForm:false,
            customer:{...row}
        });
        this.getProfiles();
        this.getHistory();

    }

The JSON object obtained from the fetch and keep it within this.state.orders looks like this:

(29) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
created:"2017-07-06T15:58:07.958Z"
customer:"59561f3f1d178e1966142ad7"
lastModified:"2017-07-06T15:58:07.958Z"
orderList:[]
orderStatusChange:Array(1)
0:{status: "5", comments: "Creado en back antes de pagar", _id: "595e5e0f60fbf65149916b7c", created: "2017-07-06T15:58:07.958Z"}
length:1
__proto__:Array(0)
shop:"59108159bc3fc645704ba508"
totalAmount:4000
__v:0
_id:"595e5e0f60fbf65149916b7b"
__proto__:Object

Capture of the object for better understanding: CAPTURE

As shown previously in the fetch, with this line this.setState({orders:responseData}) I can pass orders to the table where I want the id, the date and status to be displayed:

<DataTables
     height={'auto'}
     selectable={false}
     showRowHover={true}
     columns={HISTORY_TABLE_COLUMNS}
     data={this.state.orders}
     showCheckboxes={false}
     rowSizeLabel="Filas por página"
         />

The table called is:

const HISTORY_TABLE_COLUMNS = [
    {
        key: '_id',
        label: 'Número de pedido'
    }, {
        key: 'created',
        label: 'Fecha del pedido'
    }, {
        key: 'status',
        label: 'Estado'
    }
];

The problem comes to, when I want to print _id, created and status, the first two values are printed without any problem, but statusis within the array orderStatusChange, and I can't print it.

CAPTURE OF THE CURRENT SITUATION

How can I access status to print it on the table?

Upvotes: 1

Views: 967

Answers (2)

Dev
Dev

Reputation: 3932

If you find some option/props available in DataTable to display what you are trying, please use that.

This may sound the crude way to achieve what you are trying. But this should work. Please update below promise callback.

.then((responseData) => {
    let orders = responseData.map((order) => {
       return order.orderStatusChange ? Object.assign({}, order, {
         status: order.orderStatusChange[0].status
       }) : order;
     })
    this.setState({orders:orders})
})

In the above snippet, I am checking if the order has the key 'orderStatusChange' and it will take the status from first record and return a new object with status or else it will return the original order object.

Upvotes: 1

Mayank Shukla
Mayank Shukla

Reputation: 104379

As per DOC:

Column settings:

key         :  string       
label       :  string       
sortable    :  bool     
tooltip     :  string       
className   :  string       
render      :  function       //here
alignRight  :  bool     
style       :  object

There is a column property render, its a function, use that to return some custom element, like this:

const HISTORY_TABLE_COLUMNS = [
    {
        ....
    }, {
        ....
    }, {
        key: 'orderStatusChange',
        label: 'Estado'
        render: (staorderStatusChangetus, all) => {
            /*
               check the console values  
               i am expecting all will have the each object of the array, and 
               orderStatusChange will have that orderStatusChange array
               so you can return the result of:
               orderStatusChange.map(el => <p>{el.status}</p>)
            */ 
            console.log('value', status, all);
            return orderStatusChange.map(el => <p>{el.status}</p>)
        }
    }
];

Note: Not sure about the values so check the console output and return the result that you want.

Upvotes: 1

Related Questions