I am trying to use ag-grid with an api that gives the following code
{ "rates": { "btc": { "name": "Bitcoin", "unit": "BTC", "value": 1, "type": "crypto" }, (snip) }
And my ag-grid is set up in the following way
<AgGridReact rowSelection="multiple" rowData={rowData}> <AgGridColumn field="btc" filter={true} checkboxSelection={true} sortable={true}></AgGridColumn> <AgGridColumn field="eth" filter={true} checkboxSelection={true} sortable={true}></AgGridColumn> <AgGridColumn field="ltc" filter={true} checkboxSelection={true} sortable={true}></AgGridColumn> </AgGridReact>
So far that is giving me an error. I am not understanding why, because the code is working fine when I use a different api. The other api returns the following
{ "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" }
And my working grid is set up in the following way
<AgGridReact rowSelection="multiple" rowData={rowData}> <AgGridColumn field="name" filter={true} checkboxSelection={true} sortable={true}></AgGridColumn> <AgGridColumn field="phone" filter={true} checkboxSelection={true} sortable={true}></AgGridColumn> <AgGridColumn field="email" filter={true} checkboxSelection={true} sortable={true}></AgGridColumn> </AgGridReact>
I’ve noticed that the difference is the working api is an array of objects, while the one that is not working is an object with nested objects.
The full code is here for anyone to view
thanks in advance for your help.
Advertisement
Answer
I’ve put a demo of your code here with a few changes:
“btc”, “eth”, and “ltc” are objects themselves rather than simple fields, so having them as columns wouldn’t make much sense. Maybe you meant to iterate on these objects and view their “name”, “unit”, “value”, and “type” instead. I’ve replaced the columns with the latter 4.
These objects are inside of an object with a single field: “rates”. Therefore, in your last
.then()
you’d have tolet rates = rowData.rates
But
rates
is still an object, not an array. So you’ll also have tolet newRowData = Object.values(rates)
This
newRowData
variable is an array of objects consisting of the values of “btc”, “eth”, “ltc”, etc., like so:[{ "name": "Bitcoin", "unit": "BTC", "value": 1.0, "type": "crypto" }, { "name": "Ether", "unit": "ETH", "value": 33.13, "type": "crypto" }, ... }]
Finally, I’ve put the
console.log()
inside the last.then()
, sincefetch()
is asynchronous, and there is no guarantee thatconsole.log(rowData)
would print the newly fetched data on the console.