Search code examples
reactjsasync-awaitweather-api

React.js export async function


I'm new to React.js, so please bear with me on this one.

I built a weather API app with react.js and it works. The one thing I can't do is have my async function fetchData(e) exported such that I can access it from any component outside the scope of App.js. How do I export async fetchData so that it is recognized by all components that reside outside of App.js? Do note that the async function fetchData(e) function needs all the variables that are declared at the beginning of App.js.

I excluded my API Key from the code for obvious reasons, and I didn't include all of the code inside the fetchData function because it's very lengthy.

function App() {
  //Variables
  const API_KEY = '';
  const METRE_SECOND_TO_KM_HR = 3.6;
  const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  const options = {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  };

  const [weather, setWeather] = useState([]);
  const [geolocation, setGeolocation] = useState([]);

  async function fetchData(e) {
    //async function fetchData(e) {
    const city = e.target.elements.city.value;
    const state = e.target.elements.state.value;
    const country = e.target.elements.country.value;

    e.preventDefault();
    //fetch request with city, state and country - to get a latitude and longitude based on city name.
    const geolocation_api_request_url = `https://api.openweathermap.org/geo/1.0/direct?q=${city},${state},${country}&limit=5&appid=${API_KEY}`;
    await fetch(geolocation_api_request_url)
      .then(function (res) {
        return res.json();
      })
      .then(function (data) {
        if (city && state && country) {
          //set the latitude and longitude of the location
          setGeolocation({
            data: data,
            lat: data[0].lat,
            lon: data[0].lon,
          });
          //make a second fetch call, this time with latitude and longitude
          const weather_api_url = `https://api.openweathermap.org/data/2.5/onecall?lat=${geolocation.lat}&lon=${geolocation.lon}&exclude=minutely,hourly&appid=${API_KEY}&units=metric`;
          return fetch(weather_api_url);
        }
      })


Solution

  • https://reactjs.org/docs/context.html#updating-context-from-a-nested-component

    have a look at this context Api of react js by using this you can get this function in any component in your application and you can also update the values of it.