Search code examples
reactjsreact-nativefetch-api

Fetch Multiple times per textinput in reactnative


So bassically I am building a weather app in react native and using the weatherAPI for the weather API. So bassically What my issue is: let's say that I searched the weather for New York and it gave me 80F and I searched up the weather for Dallas BUT it gives me the same details as New York's weather.

I know that my API is getting called once but How can I make my APIcall multiple times as per as my textinput changes? Here is the code:

constructor(props) {
super(props);
this.state = {
  weatherText: "Enter",
  isLoading: true,
  locationData: [],
  currentData: []
};

}

componentDidMount(){
   this.apiCALL()
 }



apiCALL(){
     return fetch(
       `http://api.weatherapi.com/v1/current.json?key=???&q=${this.state.weatherText}`//I took out the key on purpose.
     )
       .then((response) => response.json())
       .then((responseJson) => {
         this.setState({
           isLoading: false,
           locationData: responseJson.location,
           currentData: responseJson.current,
         });
       })
       .catch((error) => {
         console.log(error);
       });
  }

Note: I took out the key to the API on purpose.

So How can I achieve this. Like I said before How can I call the API as the Textinput changes? Am I suppose to use ComponentDidMount or is there some other built-in function/method in order to achieve this?.


Solution

  • Instead of calling the api on componentDidMount, call it when the text input changes or on a submit button beside a text input.
    Say you have TextInput, use

    <TextInput placeholder="eg. New York" onChange={(val)=>this.apiCALL(val)}/>
    

    and modify the apiCALL as

    apiCALL(city){
      return fetch(
        `http://api.weatherapi.com/v1/current.json?key=???&q=${city}`//I took out the key on purpose.
      )
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({
            isLoading: false,
            locationData: responseJson.location,
            currentData: responseJson.current,
          });
        })
        .catch((error) => {
          console.log(error);
        });
    }
    

    Now this function is reusable and can be used for all the cities.