[英]How to access a state variable in getServerSideProps() in NextJS?
Hi all, I am new to NextJS.大家好,我是 NextJS 的新手。 I am building a weather application using external APIs.
我正在使用外部 API 构建天气应用程序。 I am fetching data from API and presenting it on frontend.
我正在从 API 获取数据并将其呈现在前端。
I am fetching the data using getServerSideProps()
.我正在使用
getServerSideProps()
获取数据。 But what I want is that the user/client enters the city
in the input box and then clicks and finally see the weather details of the respective city.但我想要的是用户/客户端在输入框中输入
city
,然后点击,最后看到各自城市的天气详情。
For this, I had defined a city
state in the component but now I want that city to be get accessed in getServerSideProps()
.为此,我在组件中定义了一个
city
state,但现在我希望在getServerSideProps()
中访问该城市。
How to do that?怎么做?
import Head from "next/head";
import {useState} from 'react';
import Today_highlight from "./components/Today_highlight";
import Weather_Today from "./components/Weather_Today";
import Weather_week from "./components/Weather_week";
export default function Home({ results, results1 }) {
//console.log("res1 = ",results1);
const [city, setCity] = useState('Bhopal');
const handleChange = (e) => {
setCity(e.target.value);
//console.log(city)
}
const handleSubmit = (e) => {
e.preventDefault();
window.location.reload();
}
return (
<>
<Head>
<title>Weather-Lytics</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<div className="min-h-full bg-red-400 flex flex-col lg:flex-row">
<label htmlFor="inputcity" className="w-15">Enter City</label>
<input
type="email"
className="form-control w-56 h-8"
id="inputcity"
value={city}
placeholder="Enter city"
onChange={handleChange}
/>
<button className="p-1 bg-slate-600 m-auto p-auto" onSubmit={handleSubmit}> Click</button>
<div className="bg-blue-300 w-full lg:w-1/4 lg:h-full">
<Weather_Today results={results} />
</div>
<div className="bg-green-500 w-full lg:h-full ">
<div className="min-h-full flex flex-col">
<div className="bg-yellow-400 w-full">
<Weather_week results1={results1} />
</div>
<div className="bg-orange-600 w-full">
<Today_highlight results={results} />
</div>
</div>
</div>
</div>
</>
);
}
export async function getServerSideProps({query}) {
//hereI want to access the city state
//query.term = city;
if(!query.term)
query.term = 'Bhopal'
//api-1
const url = `https://api.openweathermap.org/data/2.5/weather?q=${query.term}&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;
const res = await fetch(url);
const data = await res.json();
//console.log(data);
//api-2
const url1 = `http://api.openweathermap.org/data/2.5/forecast?q=${query.term}&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;
const res1 = await fetch(url1);
const data1 = await res1.json();
//console.log(data1);
return {
props: {
results: data,
results1: data1,
},
};
}
handleSubmit
is correct way to fetch data?handleSubmit
中的代码是否是获取数据的正确方法? State variables from the client-side can't be accessed from getServerSideProps
as it runs on the server. State 客户端的变量无法从
getServerSideProps
访问,因为它在服务器上运行。 You have to pass the data through query params to make it available server-side.您必须通过查询参数传递数据以使其在服务器端可用。
To pass city
as a query parameter to be picked up in getServerSideProps
you can use router.push
inside the handleSubmit
function.要将
city
作为查询参数传递给getServerSideProps
,您可以在handleSubmit
function 中使用router.push
。
const handleSubmit = (e) => {
e.preventDefault();
router.push(`/?term=${city}`);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.