genus20
genus20

Reputation: 23

Async function call repeated inside of class component

I've created an Asynchronous function to call a weather API that will return the requested information submitted. The function works fine however when I call this function inside of a Class Component the result is returned twice. This isn't exactly a breaking bug but I'd rather not have two API calls occurring if not necessary and I'm curious as to why this method is being called twice in the first place.

Here is my code.


async function submitQuery(props) {
  //Incase I decide to add aditional parameters such as city, country etc.. I've decided to place the zip property in an object so I can just
  //add additional properties in the submissions object
  const submission = {
    zip: props,
  };

  if (!Number(props)) return console.log("this is not a number");

  const { error } = await validate(submission);
  if (error) return console.log(error.message);

  const config = {
    method: "get",
    url: `https://api.openweathermap.org/data/2.5/weather?zip=${props}&appid=${apiKey}`,
    headers: {},
  };

  /*
  const query = await axios(config).then(function (response) {
    const result = response.data.main;
    return result;
  });
  */

  //console.log(query);
  return 4;
}
class WeatherReport extends React.Component {
  getResults = async () => {
    const result = await submitQuery("08060");
    console.log(result);
  };

  render() {
    return (
      <div className="reportContainer">
        <WeatherCard getResults={this.getResults} />
      </div>
    );
  }
}

const WeatherCard = ({ getResults }) => {
  getResults();
  return <div></div>;
};

Upvotes: 1

Views: 692

Answers (1)

branks
branks

Reputation: 106

The problem is that you're calling getResults in the render method of WeatherCard, move it to a useEffect so its not called every time

const WeatherCard = ({ getResults }) => {
    React.useEffect(() => {
        getResults();
    }, [getResults]);
    return <div></div>;
};

Upvotes: 3

Related Questions