I am working on putting the results of a Currency API into a data table! I have set the api up in an apex class and the data comes through fine but I can't seem to get the data to display in the table can anyone tell me where I am going wrong? I think it's on the formatExchangeData function I have written as I am trying to map the data, Maybe a map isn't what I need but not sure what else to do! I am quite rusty with JS so any help/examples would really benefit me! THANK YOU!!
API CLASS:
public with sharing class apiCalloutClass {
@AuraEnabled(cacheable=true)
public static Map<string, object> getExchange() {
HttpRequest httpRequest = new HttpRequest();
httpRequest.setEndpoint('http://data.fixer.io/api/latest?access_key=0890b65238c39945ef817557bee851ed');
httpRequest.setMethod('GET');
Map<String, Object> exchangeJsonData = new Map<string, Object>();
String strResponse = null;
try {
Http http = new Http();
HttpResponse httpResponse = http.send(httpRequest);
if(httpResponse.getStatusCode()== 200){
strResponse = httpResponse.getBody();
} else {
throw new CalloutException(httpResponse.getBody());
}
} catch (Exception ex) {
throw ex;
}
if(!String.isBlank(strResponse)){
exchangeJsonData = (Map<String, Object>)JSON.deserializeUntyped(strResponse);
}
if(!exchangeJsonData.isEmpty()){
return exchangeJsonData;
}else {
return null;
}
}
}
LWC JS:
import { LightningElement, track } from 'lwc';
import apiCalloutData from '@salesforce/apex/apiCalloutClass.getExchange';
const columns = [
{label: 'Date', value: 'date'},
{label: 'Rates', value: 'rates'},
{label: 'Base Currency', value: 'base'}
]
export default class ApiCalloutLWC extends LightningElement {
result=[];
columns = columns;
connectedCallback(){
this.fetchCurrency();
}
fetchCurrency(){
apiCalloutData().then(response => {
console.log(response);
this.formatExchangeData(response.data);
console.log(this.result);
}).catch(error=>{
console.error(error);
})
}
formatExchangeData(res){
//issue seems to be here where it can't read the map I am creating of the API data
this.result = res.map((item)=>{
return { ...item, id: id, date: date, rates: rates, base:base}
})
}
}
HTML:
<template>
<lightning-card title="Currency Exchange Rate" icon-name="standard:currency">
<lightning-datatable
key-field="id"
data={result}
columns={columns}
hide-checkbox-column="true">
</lightning-datatable>
</lightning-card>
</template>