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.

3 Answers 3

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))
  }
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

I tried it and got an error "this.getRates(...) is undefined" do you have idea where it could came from ?
You might not have bind the this context for getRates() function. Check that
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.