medinaz
medinaz

Reputation: 23

TypeError: Cannot read property 'undefined' of undefined

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

Answers (2)

Shubham Dixit
Shubham Dixit

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

Dennis Vash
Dennis Vash

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

Related Questions