Reputation: 151214
To experiment with Next.js, I created an empty Next.js project, and added some code to fetch data for weather:
export default function Home() {
const [data, setData] = useState(null);
useEffect(() => {
fetch("https://api.weather.gov/gridpoints/MTR/84,105/forecast")
.then((res) => res.json())
.then((d) => setData(d));
}, []);
const details = data && data.properties.periods[0];
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
Hello world
{details && (
<div>
<h2>San Francisco Forecast</h2>
<img src={details.icon} />
<p>
Temperature: {details.temperature}°{details.temperatureUnit} /{" "}
{Math.round(((details.temperature - 32) * 50) / 9) / 10}°C
</p>
<p>{details.shortForecast}</p>
<p>{details.detailedForecast}</p>
<p>{new Date(details.startTime).toLocaleString()}</p>
</div>
)}
</main>
</div>
)
}
Demo: https://codesandbox.io/s/staging-snow-6tvqc?file=/pages/index.js
and the standalone page: https://6tvqc.sse.codesandbox.io/
How can we make the following command
curl https://6tvqc.sse.codesandbox.io/
be able to show the content as if on the webpage? (so should be able to have Temperature
and the numbers after it).
Upvotes: 1
Views: 1333
Reputation: 660
Do data fetching in these functions.
Next.js provides 3 functions for data fetching. You have to export them from your page.
You have to return data in a format and it will be injected in props of your react component.
You can also provide fallback on props to dynamically render pages, like you don't have to make every page static (using GetStaticProps/Paths). Make only some of them and Next.js will make remaining on request and will cache them for next request.
Upvotes: 1