Reputation: 23
I have this array:
super(props);
this.state = {
data: [{
baseCurrency: 'GBP',
baseAmount: 0,
convertToCurrency: 'USD',
rates: [],
currencies: []
},
]
}
When i try to access it inside the render() function it gives me the error
const {currencies,rates,baseCurrency,baseAmount,convertToCurrency} = this.state.data;
const result = Number.parseFloat(baseAmount * rates[convertToCurrency]).toFixed(2);
If i am not declaring this.state with an array then this problem will not happen.
Upvotes: 1
Views: 247
Reputation: 1
Destructure the data like this
let res = {
data: [{
baseCurrency: 'GBP',
baseAmount: 0,
convertToCurrency: 'USD',
rates: [],
currencies: []
}, ]
}
const {
data: [{
baseCurrency,
baseAmount,
convertToCurrency
}]
} = res;
console.log(baseCurrency, baseAmount, convertToCurrency);
Upvotes: 1
Reputation: 53874
You can spread only a specific object because this.state.data
is an array:
const [
{ currencies, rates, baseCurrency, baseAmount, convertToCurrency },
] = this.state.data;
And more readable:
const [firstItem] = this.sate.data;
const {
currencies,
rates,
baseCurrency,
baseAmount,
convertToCurrency,
} = firstItem;
Upvotes: 1