简体   繁体   中英

REACT.js variables not accepted in api request

I'm trying to make my code more efficient and reusable by adding variables on my requests and console.log. But for some reason its not working and I can't figure out why: full code can be found at: https://codesandbox.io/s/wispy-lake-6h051

This works:

  state = {
    lastWeek: '2020-11-09',
    today: '2020-11-12',
    selectedBase: 'USD',
    firstDateValues: null,
    fifthDateValues: null
  };

  getAPI = async() => {
    const START_DATE = this.state.lastWeek;
    const END_DATE = this.state.today;
    const BASE = this.state.selectedBase;
    
    const response = await fixer.get(`?start_at=${START_DATE}&end_at=${END_DATE}&base=${BASE}`, {
    });
    console.log(BASE) ---> output: USD
    console.log(response.data.rates[START_DATE].USD) --> correct data
}

But this doesn't:

  state = {
    lastWeek: '2020-11-09',
    today: '2020-11-12',
    selectedBase: 'USD',
    firstDateValues: null,
    fifthDateValues: null
  };

  getAPI = async() => {
    const START_DATE = this.state.lastWeek;
    const END_DATE = this.state.today;
    const BASE = this.state.selectedBase;
    
    const response = await fixer.get(`?start_at=${START_DATE}&end_at=${END_DATE}&base=${BASE}`, {
    });
    console.log(BASE) ---> output: USD
    console.log(response.data.rates[START_DATE].BASE) --> output: undefined 
}

Why?

What you need to do is to change

response.data.rates[START_DATE].BASE

to

esponse.data.rates[START_DATE][BASE]

because if you are using .BASE , it means BASE key, not your key from BASE variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM