'How to access a state variable in getServerSideProps() in NextJS?
Intro
Hi all, I am new to NextJS. I am building a weather application using external APIs. I am fetching data from API and presenting it on frontend.
What I want?
I am fetching the data using 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.
what I had done?
For this, I had defined a city state in the component but now I want that city to be get accessed in getServerSideProps().
How to do that?
Code
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,
},
};
}
Also I am in doubt whether the code inside handleSubmit is correct way to fetch data ?
Solution 1:[1]
State variables from the client-side can't be accessed from getServerSideProps as it runs on the server. 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.
const handleSubmit = (e) => {
e.preventDefault();
router.push(`/?term=${city}`);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
