0

I've got a function getData() that grabs a JSON object of the current weather conditions. While I can see the JSON object in the console, I can't seem to pass it to a usable variable. What am I missing here?

const getData = () => {
  let url = `https://api.openweathermap.org/data/2.5/weather?q=Asheville&appid=${key}`
  fetch(url)
      .then((response) => {
        return response.json();
      })
      .then((response) => {
         console.log(response);
      })
      .catch((err) => {
        console.log(err);
      })
}

function App() {
  let data = getData();
  console.log(data);
  return (
    <div className="App">
      <Forecast />
    </div>
  );
}

I've tried it a couple ways and can't get it to work. Also for some reason it logs in the console twice and I'm not sure why. Any advice is greatly appreciated!

2

1 Answer 1

1

You can use react hooks

const useGetData = () => {
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    let url = `https://api.openweathermap.org/data/2.5/weather?q=Asheville&appid=${key}`;
    fetch(url)
      .then((response) => response.json())
      .then((response) => setData(response))
      .catch((err) => setError(err));
  }, []);

  return [data, error];
};

function App() {
  let [data, error] = useGetData();

  return (
    <div>
      <p>{JSON.stringify(data, null, 2)}</p>
      {error && <p>There's been an error: {error}</p>}
    </div>
  );
}

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, thank you I'll go do some research on hooks.
@dishbin If you find my answer useful, you should mark it as correct.
@dishbin remember to use an if statement to check if data exists before rendering.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.