I have a server component in next.js 13.4 and on first load I am calling an api to get the data of weather, it is working fine.
Now I want to change the city using a form input. Which I am doing using server actions. But how to update the data of local variable weatherData
to UI is update with new weather data?
import styles from "./page.module.css";
import { notFound } from "next/navigation";
import { revalidatePath } from "next/cache";
async function getWeatherData(address) {
const weatherData = await fetch(
"http://localhost:3000/api/weather?address=" + address,
{ cache: "no-cache", tags: ["weather"] }
);
if (!weatherData.ok) return notFound();
return weatherData.json();
}
const Home = async () => {
const weatherData = (await getWeatherData("lahore")).data;
// console.log(weatherData);
async function changeCityAction(data) {
"use server";
const city = data.get("cityName")?.toString();
const weatherData = (await getWeatherData(city)).data;
console.log(weatherData);
// Here, how to update UI with this new data
revalidatePath("/weather");
}
return (
<main className={styles.main}>
<article className={styles.widget}>
<form className={styles.weatherLocation} action={changeCityAction}>
<input
className={styles.input_field}
placeholder="Enter city name"
type="text"
id="cityName"
name="cityName"
/>
<button className={styles.search_button} type="submit">
Seach
</button>
</form>
<div className={styles.icon_and_weatherInfo}>
<div className={styles.weatherIcon}>
{weatherData?.weather[0]?.description === "rain" ||
weatherData?.weather[0]?.description === "fog" ? (
<i
className={`wi wi-day-${weatherData?.weather[0]?.description}`}
></i>
) : (
<i className="wi wi-day-cloudy"></i>
)}
</div>
<div className={styles.weatherInfo}>
<div className={styles.temperature}>
<span>
{(weatherData?.main?.temp - 273.5).toFixed(2) +
String.fromCharCode(176)}
</span>
</div>
<div className={styles.weatherCondition}>
{weatherData?.weather[0]?.description?.toUpperCase()}
</div>
</div>
</div>
<div className={styles.place}>{weatherData?.name}</div>
</article>
</main>
);
};
export default Home;