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

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(``);
        const json = await res.json();
    }, 45000);

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

  return (
      <h1>Current Weather:</h1>

export const getStaticProps: GetStaticProps = async () => {
  const res = await fetch(``);
  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