function search() {
const router = useRouter();
const { location, startDate, endDate, numOfGuests } = router.query;
const formattedStartDate = format(new Date(startDate), "dd, MMMM yyyy");
const formattedEndDate = format(new Date(endDate), "dd, MMMM yyyy");
const range = `${formattedStartDate} - ${formattedEndDate}`;
return(...);
}
export default search;
Using React/Next.js.
I am trying to create a formatted date using date-fns. The problem seems that when i input the variable of startDate
into the new Date()
ex: new Date(startDate)
, it gives me the error. When i manually hard code the value of startDate
instead, it works as needed, example: new Date("2022-01-28T05:00:00.000Z")
. I even tried making startDate
into a string by startDate.toString()
and still doesn't work.
startDate
is coming from date-fns DateRangePicker allowing you to select two dates. I am then pushing it through next.js router as a query
const search = () => {
router.push({
pathname: "/search",
query: {
location: searchInput,
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
numOfGuests,
},
});
};
CodePudding user response:
I figured out my problem. Everything works fine and the code should have worked as intended. The problem was coming from using nextJs, useRouter()
. To access the router I needed to use useRouter()
, example: const router = useRouter();
. Then to access the query data i've set up within the router would be such as: const { location, startDate, endDate, numOfGuests } = router.query;
.
To use useRouter
it needs to be in a proper component function starting with a capitalized name. My problem was it was lowercased. Example ; function search() {...}
instead of, function Search() {...}
. From here i will keep the file name of search.js
lowercased for address bar router query purposes.