I am working on a nextjs project that is a calendar. when country and year changes calendar should change and I use a holidays API. API url contains country and year parameters(https://localhost:5001//holiday?&country=${country}&year=${year}
). SO I need to pass country and year , In Holiday.tsx
I use a Drop down for select country and year.
I struggled at data fetching. How Can I pass these selected country and year values to index.tsx
. I don't use dynamic paths. I have only index.ts.
api.ts
import axios from "axios";
import { GetAllHolidaysData } from "../interfaces/GetAllHolidaysData";
process.env.NODE_TLS_REJECT_UNAUTHORIZED;
const http = axios.create({ baseURL: process.env.NEXT_PUBLIC_API });
export const GetAllHolidays = (country: string, year: number) => {
console.log(country, year);
return http.get<GetAllHolidaysData>(
`/holiday?&country=${country}&year=${year}`
);
};
index.tsx
const Home: NextPage<{ holidays: GetAllHolidaysData }> = ({ holidays }) => {
return (
<>
<Holidays holidays={holidays}/>
</>
);
};
export const getServerSideProps: GetServerSideProps = async () => {
// let country = "ro";
// let year = "2021";
let holidays: GetAllHolidaysData;
try {
const { data } = await GetAllHolidays(country, year); // I struggled at this line how to bind country and year those are selected in Holiday.tsx file using a dropdwon
holidays = data;
} catch (error) {
console.log(error);
}
return {
props: {
holidays,
},
};
};
export default Home;
Holiday.tsx - conuntry and year changes here
const Holidays: NextPage<data> = ({ holidays }) => {
const [selectedYear, setselectedYear] = useState(currentYear);
const [selectedCountry, setselectedCountry] = useState(countries[169]);
const countryChangeHanlder = (e) => {
GetAllHolidays(e.value, year);
// setCountry(e.label);
setselectedCountry(e);
console.log(selectedCountry);
};
const yearChangeHanlder = (e) => {
const countryCode = Object.entries(selectedCountry)[0].map((i) => i)[1];
GetAllHolidays(String(countryCode), e.value);
setYear(e.value);
setselectedYear(e);
};
}
Short answer:
You can't do it in
getServerSideProps
using the selection from the dropdown, given that the dropdown is on the page you want to return using thisgetServerSideProps
. Instead, you should do it in the component itself -const Home: NextPage
orHoliday.tsx
.Explanation:
getServerSideProps
is called on the server before the page is returned to the client. You can check it here.Your dropdown selection is available after the page is returned (and rendered), so that's where you have access to the values, hence you're able to make a request using the selection
Updated:
You could do smth like this: