简体   繁体   中英

get value for api calling from other functions state REACTJS

So far I am calling an api in componentDidMount() and set it to select option. also call another conditional api from user input. But Problem is it is calling the api non stop.

**getRates(){
    const base = this.handlePrint(this.state.value);
    fetch(`https://exchangeratesapi.io/api/latest?base=${base}`)
        .then(data => data.json())
        .then(data =>{
           this.setState({
               rate: data.rates,
           })
            console.log(data.rates)
        })
        .catch(err => console.log(err))
}**

And my console screen shot:

console

I just need one time api call based on user input.

full code: https://codeshare.io/5MwXzq

I think there is a problem with the state but I am new in reactjs and could not understand how to solve that. Anyone can help please.

This is happening not because of anything in componentDidMount()

Based on the code you shared on codeshare.io , you're calling getRates() function in your render() method. Also, you're setting the state using setState within the getRates method. This causes a re-render, calling render() again, and so you get the infinite loop of calls.

Remove the call to getRates() from your render method and it'll work.

EDIT:

Since there were small changes but strewn across your code to get it to work, I've modified your class and posting it here:

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currencies: [],
      value: "?",
      base: "?",
      input: "?",
      rate: 0
    };
    this.getRates = this.getRates.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handlePrint = this.handlePrint.bind(this);
  }

  componentDidMount() {
    fetch("https://exchangeratesapi.io/api/latest?symbols=USD,GBP,AUD,JPY")
      .then(data => data.json())
      .then(data => {
        const currencies = [];
        currencies.push(
          data.base,
          ...Object.entries(data.rates).map(rates => rates[0])
        );

        this.setState({
          currencies
        });
      })
      .catch(err => console.log(err));
  }

  getRates() {
    const base = this.handlePrint();
   console.log(this.state); fetch(`https://exchangeratesapi.io/api/latest?base=${base}`)
      .then(data => data.json())
      .then(data => {
        this.setState({
          rate: data.rates
        });
        console.log(data.rates);
      })
      .catch(err => console.log(err));
  }

  //Dropdown
  DropDown = function(list) {
    return <option value={list}>{list}</option>;
  };

  handleChange(e) {
    this.setState({ value: e.target.value });
  }

  handlePrint() {
    console.log(this.state)
    if (this.state.value) {
      return this.state.value;
    }
  };
  render() {
    const { currencies } = this.state;
   // const input = this.getRates();

    return (
      <div>
        <span>SELECT your Base: </span>
        <select autoFocus onChange={this.handleChange}>
          <option inputcurrency={currencies} selected data-default>
            SELECT BASE
          </option>
          {currencies.map(this.DropDown)}
        </select>
        <button onClick={this.getRates}>GET RAtes</button>
        <p>selected base:{this.handlePrint()} </p>
      </div>
    );
  }
}

The changes are: 1. Bound getRates() method in the constructor 2. Removed the call to getRates() in render start 3. Removed unnecessary items passed to handlePrint 4. Changed the button onClick to point to getRates

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