0

I've been trying to figure out my invalid time value issue. I built an airbnb clone and I'm using daterangepicker to work with the calendar, save the range selected in state and use that information to display it as a placeholder in the search bar after the search. I followed the video online precisely but for some reason I get this error and the person online didn't. I searched related posts here but nothing really helped so hopefully someone can help me resolve the issue so that I can finally deploy it. It all works fine without any issues on my local server but once I refresh the results page it defaults to this error

  • RangeError: Invalid time value in pages/search.js

    
      15 | //ES6 destructuring
      16 |   const { location, startDate, endDate, noOfGuests} = router.query;
    > 17 |   const formattedStartDate = format(new Date(startDate), "MM/dd/yy");
         |                                    ^
      18 |   const formattedEndDate = format(new Date(endDate), "MM/dd/yyyy");
      19 |   const range = `${formattedStartDate} - ${formattedEndDate}`;
    
    

Here is the search component:

```
import React from 'react'
import Header from '../components/Header'
import Footer from '../components/Footer'
import { useRouter } from 'next/dist/client/router'
import {format} from 'date-fns'
import InfoCard from '../components/InfoCard'
import searchResults from '../files/searchResults.JSON'




function Search() {
    const router = useRouter();

  //ES6 destructuring
    const { location, startDate, endDate, noOfGuests} = router.query;
    const formattedStartDate = format(new Date(startDate), "MM/dd/yy");
    const formattedEndDate = format(new Date(endDate), "MM/dd/yyyy");
    const range = `${formattedStartDate} - ${formattedEndDate}`;



    return (
    <div>
        <Header
             placeholder= {`${location} | ${formattedStartDate}| ${formattedEndDate} | ${noOfGuests} guests `}
        />
            <main className='flex'>
                <section className='flex-grow pt-14 px-6'>
                    <p className='text-xs '>500+ Stays - {range} - {noOfGuests} guests</p>

                    <h1 className='text-3xl font-semibold mb-6 mt-2'>Stays in {location}</h1>

                    <div className='hidden md:inline-flex mb-5 space-x-3 text-gray-800 whitespace-nowrap'>
                        <p className='button'>Cancellation Flexibilty</p>
                        <p className='button'>Type of Place</p>
                        <p className='button'>Price</p>
                        <p className='button'>Rooms and Beds</p>
                        <p className='button'>More Filters</p>
                    </div>
                    <div className='flex flex-col'>
                        {searchResults.map(({ key, img, description, location, star, price, total, title, long, lat }) => (
                            <InfoCard 
                                key={key}
                                img= {img}
                                location = {location}
                                title={title}
                                description={description}
                                star={star}
                                price={price}
                                total={total}
                                long={long}
                                lat={lat}
                            />
                        ))}
                    </div>
                    
                </section>
            </main>

        <Footer />
    </div>
  )
}

export default Search;
```

And here is the Header component containing the daterangepicker

```
import React from 'react';
import Image from 'next/image';
import {SearchIcon, GlobeAltIcon, MenuIcon, UserCircleIcon, UserIcon} from "@heroicons/react/solid"
import {useState} from "react"
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
import { DateRangePicker } from 'react-date-range';
import { useRouter } from 'next/dist/client/router';



function Header({placeholder}) {

    const [searchInput, setSearchInput] = useState("");
    const [startDate, setStartDate] = useState(new Date());
    const [endDate, setEndDate] = useState(new Date());
    const [noOfGuests, setNoOfGuests] = useState(1);
    const router = useRouter();
    const selectionRange = {
        startDate: startDate,
        endDate: endDate,
        key: "selection"
    };

    const handleSelect = (ranges) => {
        setStartDate(ranges.selection.startDate); 
        setEndDate(ranges.selection.endDate);
        };
    
    
    const resetInput = () => {
        setSearchInput("");
    };

    const search = () => {
        router.push({
           pathname: '/search',
            query: {
                location: searchInput,
                startDate: startDate.toISOString(),
                endDate: endDate.toISOString(),
                noOfGuests,
            }
        });
    }

  return (
    <header className='sticky top-0 z-50 grid grid-cols-3 bg-white my-0 shadow-md p-5 w-full md:px-10'>
        <div onClick={() => router.push("/")} className="relative flex items-center h-10 cursor-pointer my-auto">
            <Image src="https://links.papareact.com/qd3" 
                layout="fill"
                objectFit="contain"
                objectPosition="left"
                alt=''
            />
        </div>
        
        <div className='flex item-center md:border-2 rounded-full py-2 md:shadow-sm'>
            <input value={searchInput} onChange={(e) => setSearchInput(e.target.value)}
            type="text" placeholder={placeholder} className='pl-5 bg-transparent outline-none flex-grow text-sm text-gray-600 placeholder-gray-400' />
            <SearchIcon onClick={search} className='hidden md:inline-flex h-8 bg-red-400 text-white rounded-full p-2 cursor-pointer md:mx-2' />
        </div>
       
        <div className='flex items-center space-x-4 justify-end text-gray-400'>
            <p className='hidden md:inline cursor-pointer'>Become a Host</p>
            <GlobeAltIcon className='h-6 cursor-pointer' />
            <div className='flex items-center space-x-2 border-2 p-2 rounded-full'>
                <MenuIcon className='h-6 cursor-pointer'/>
                <UserCircleIcon className='h-6 cursor-pointer' />
            </div>
        </div>

        {searchInput && (
            <div className='flex flex-col col-span-3 mx-auto'>
                <DateRangePicker 
                    ranges={[selectionRange]}
                    minDate={new Date()}
                    rangeColors={["#FD5B61"]}
                    onChange={handleSelect}
                />

                <div className='flex items-center border-b mb-4'>
                    <h2 className='text-2xl flex-grow font-semibold'>Number of Guests</h2>
                    <UserIcon className='h-5' />
                    <input onChange={e => setNoOfGuests(e.target.value)} value={noOfGuests} type="number" min="1" className='w-12 pl-2 text-lg outline-none text-red-400' />
                </div>

                <div className='flex'>
                   <button className='flex-grow text-gray-500' onClick={search}>Search</button> 
                   <button className='flex-grow text-red-400' onClick={resetInput}>Cancel</button> 
                </div>

            </div>
        )}
    </header>
  )
}

export default Header
```
  • The date you're trying to format is most likely undefined on the first render, see [useRouter/withRouter receive undefined on query in first render](https://stackoverflow.com/questions/61040790/userouter-withrouter-receive-undefined-on-query-in-first-render). Try calling `format` only if a date is actually defined, e.g. `const formattedStartDate = startDate ? format(new Date(startDate), "MM/dd/yy") : ""`. – juliomalves Sep 26 '22 at 17:28
  • My gosh you are a genius that literally fixed the problem!! And when I refresh it it keeps displaying the formatted date in the search bar. I don't understand why exactly it fixes the problem but this great!! I also added a marker on the Mapbox I installed which is not displayed for some reason. I'm not sure if you're familiar with Mapbox and ReactMapGL but maybe you can take a look at it. It is the Map.js component https://github.com/fabioc1101/airbnb – fabiocattolico Oct 01 '22 at 14:59
  • 1
    I'd recommend creating a new question for that issue. – juliomalves Oct 01 '22 at 15:01

0 Answers0