0

I am making currency converter with react. I added swap button, which task is to change currency users want to sell with the one they want buy. So I have to change rates whenever its done here is function responsible for that:

getRates(currencyShortcut){
    fetch('https://api.fixer.io/latest?base='+currencyShortcut)
      .then(response => response.json())
      .then(parsedJson => this.setState({currencyRates:parsedJson}))
      .catch(error => console.log('fetch error - ', error))
  }

and swap function looks like that:

swapValues(e){
    e.preventDefault();
    const {currency1,currency2} = this.state;
    this.getRates(currency2.shortcut,()=>{
      this.setState({
        currency1: currency2,
        currency2:currency1
      })
    });
  }

but despite getRates is executed, the callback where I set state isn't. I seen When to use React setState callback, I want to do the same but another way around.

Jake11
  • 801
  • 2
  • 11
  • 24

3 Answers3

2

You need to accept the callback argument in getRates and the call it after the setState.

getRates(currencyShortcut, callBack){
    fetch('https://api.fixer.io/latest?base='+currencyShortcut)
      .then(response => response.json())
      .then(parsedJson => this.setState({currencyRates:parsedJson},
          ()=>callBack()))
      .catch(error => console.log('fetch error - ', error))
  }
Tirth Shah
  • 614
  • 4
  • 7
2

You should return from getRates() call and it will get you the promise returned, and afterwards you can fire a callback with .then() in swapValues() function.

getRates(currencyShortcut){
    return fetch('https://api.fixer.io/latest?base='+currencyShortcut)
      .then(response => response.json())
      .then(parsedJson => this.setState({currencyRates:parsedJson}))
      .catch(error => console.log('fetch error - ', error))
  }

swapValues(e){
    e.preventDefault();
    const {currency1,currency2} = this.state;
    this.getRates(currency2.shortcut).then(()=>{
      this.setState({
        currency1: currency2,
        currency2:currency1
      })
    });
  }

This approach should work.

Aaditya Thakkar
  • 1,750
  • 13
  • 13
1

You're calling getRates with two arguments, while the function is only taking the first one. If you accept a second cb argument in getRates, you could then call it from setState({...}, cb()) and get your callback executed.

Miguel Calderón
  • 3,001
  • 1
  • 16
  • 18