1

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) => {
                let orders = responseData.map((order) => {
                    return order.orderStatusChange ? Object.assign({}, order, {
                        status: order.orderStatusChange[0].status
                    }) : order;
                });
                this.setState({orders:orders});
                console.log("Log del responseData");
                console.log(responseData);
                console.log(responseData.orderStatusChange[0]);

            })
            .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 kept 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

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, date, status and price 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',
        style:{width: '37%'}
    }, {
        key: 'created',
        label: 'Fecha del pedido',
        style:{width: '33%'}
    }, {
        key: 'status',
        label: 'Estado',
        style:{width: '13%'}
    }, {
        key: 'totalAmount',
        label: 'Total',
        style:{width: '17%'}
    }
];

How can I format the price (totalAmount) to have 2 decimals and print next to it the € symbol?

CAPTURE FOR BETTER UNDERSTANDING

0

3 Answers 3

1

This solution works fine with node module material-ui-datatables version 0.18.0

You can use render method in column settings to work on the column data.

const currencyToAppend = '€';
const HISTORY_TABLE_COLUMNS = [
  {
    ....
  }, {
    ....
  }, {
    key: 'totalAmount',
    label: 'Total',
    style:{width: '17%'}
    render: (amount, all) => {
        console.log(amount);
        console.log(all);
        return amount + ' ' + currencyToAppend;
    }
  }
];
Sign up to request clarification or add additional context in comments.

15 Comments

It hasn't worked. My "all" is an unsused parameter, what is the purpose of it?
@Calicorio2, can you try printing both 'amount' and 'all'. I am too not aware. I checked the npm module npmjs.com/package/material-ui-datatables which you are using. If you are getting 'amount' in console, this should work.
Ok I'll try it.
ohh is it. Ok give me some time will try and update you.
'all' gives the total data object. I think you might be using the older version of DataTables. I just installed the latest "material-ui-datatables": "^0.18.2". Pl check yours
|
1

While iterating data in table please do the following.

totalAmount.toFixed(2) + " €"

Update: I would suggest this change should be done from backend, But any how for now you can handle it in map iterator where you are setting orders like following

const currencyToAppend = ' €';

    let orders = responseData.map((order) => {
        return order.orderStatusChange ? Object.assign({}, order, {
          status: order.orderStatusChange[0].status
        },{
            totalAmount: order.totalAmount.toFixed(2) + currencyToAppend
        }) : Object.assign({}, order, {
            totalAmount: order.totalAmount.toFixed(2) + currencyToAppend
        });
    });

I hope this will solve your problem.

5 Comments

Should I create another map function and iterate there?
@Calicorio2 Hey, am not sure about how your <DataTables /> component works. is it custom component or imported from any library ?
I've tried your answer updated and the result is a blank table. Nothing prints on it.
It goes straight to the catch "error"in the fetch function.
Please print development errors on console, like this .catch(function(err) { console.log(err); }
0

To complement @dev's answer, I'd suggest to have render the cell as a function as that gives you more control

Check out the codesandox demo https://codesandbox.io/s/0VVwq645L

const HISTORY_TABLE_COLUMNS = [
  {
    key: "_id",
    label: "Número de pedido",
    style: { width: "37%" },
    value: item =>
      <code>
        {item._id}
      </code>
  },
  {
    key: "created",
    label: "Fecha del pedido",
    style: { width: "33%" },
    value: item => <Time value={item.created} />
  },
  {
    key: "status",
    label: "Estado",
    style: { width: "13%" },
    value: item =>
      <span>
        {item.status}
      </span>
  },
  {
    key: "totalAmount",
    label: "Total",
    style: { width: "17%" },
    value: item => <Amount value={item.totalAmount} currency="€"} />
  }
];

3 Comments

I've tried implementing part of your propose, but it hasn't worked either. I'll edit my question to show you what I've done.
I see that your data values are constructed in situ, so in my case are you suggesting to add a new parameter in the JSON object called currency to retrieve it?
Used mock data. It's upto you on how you want to append the currency. Edited, to hardcode the currency in the sample code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.