nextjs isr page that regenerates every 45 seconds. the page should fetch the latest weather for a zip code. in typescript

index.ts
import { GetStaticProps, NextPage } from 'next';
import { useState, useEffect } from 'react';

interface WeatherProps {
  weather: string;
}

const WeatherPage: NextPage<WeatherProps> = ({ weather }) => {
  const [currentWeather, setCurrentWeather] = useState(weather);

  useEffect(() => {
    const interval = setInterval(() => {
      (async () => {
        const res = await fetch(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=YOUR_ZIP_CODE`);
        const json = await res.json();
        setCurrentWeather(json.current.condition.text);
      })();
    }, 45000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <h1>Current Weather:</h1>
      <p>{currentWeather}</p>
    </div>
  );
};

export const getStaticProps: GetStaticProps = async () => {
  const res = await fetch(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=YOUR_ZIP_CODE`);
  const json = await res.json();
  return { props: { weather: json.current.condition.text } };
};

export default WeatherPage;
1037 chars
38 lines

In this example, we define a WeatherPage component that uses state to keep track of the current weather using the useState hook. We use the useEffect hook to run an async function every 45 seconds to fetch the latest weather data from the Weather API using fetch, and then update the state with the new weather data.

We also define a getStaticProps function that fetches the initial weather data and returns it as props, so that the page can be rendered with the initial data immediately. We use NextPage and GetStaticProps types to make sure our page component has the expected props and static generation function signatures.

gistlibby LogSnag