From the course: Master React 19 and Next.js 16 with Hands-On Projects and Real-World Applications

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Build a useEffect to fetch weather data when a city is selected

Build a useEffect to fetch weather data when a city is selected

Welcome to this session on fetching weather data with UseEffect in your React Weather app. Our goal is to build a UseEffect hook that fetches weather data from the OpenMedio API whenever a user selects a city. This UseEffect will trigger when the selected city changes, use the city's coordinates to make the API call, and store the raw JSON response for later processing in our app. Let's dive in. We want to add the core logic for fetching weather data when the selected city changes. Now, you will see me import the UseEffect hook from React. We'll use this to perform side effects, such as fetching data, in our component. Let's add the UseEffect hook to our component. It's currently empty and set to run only once after the initial render because of the empty dependency array. I am adding SelectedCity to the dependency array of the UseEffect hook. This means the effect will rerun whenever the value of SelectedCity changes, which is exactly what we want. Let's add a check within the…

Contents