Prevent booking if already booked

Join the 2022 Full-Stack Web Dev Bootcamp!


This post is part of a new series where we build a clone of Airbnb with Next.js. See the first post here.

Now there’s a problem if we try to book some dates that are already booked.

We need to make good use of our /houses/check endpoint to check if in the dates we want to book, some are already booked!

We do this by adding this canReserve() function to pages/houses/[id].js:

pages/houses/[id].js

const canReserve = async (houseId, startDate, endDate) => {
  try {
    const response = await axios.post(
      'http://localhost:3000/api/houses/check',
      { houseId, startDate, endDate }
    )
    if (response.data.status === 'error') {
      alert(response.data.message)
      return
    }

    if (response.data.message === 'busy') return false
    return true
  } catch (error) {
    console.error(error)
    return
  }
}

This function is calling the server-side /api/houses/check endpoint we created previously, and if we get ‘busy’ as a message in the response, we return false.

We can use this boolean return value to disallow going on with the booking, in the “Reserve” button onClick callback function we already wrote.

That function now is:

pages/houses/[id].js

<button
  className="reserve"
  onClick={async () => {
    try {
      const response = await axios.post('/api/reserve', {
        houseId: house.id,
        startDate,
        endDate
      })
      if (response.data.status === 'error') {
        alert(response.data.message)
        return
      }
      console.log(response.data)
    } catch (error) {
      console.log(error)
      return
    }
  }}
>
  Reserve
</button>

We do it as the first thing:

pages/houses/[id].js

<button
  className='reserve'
  onClick={async () => {
	if (!(await canReserve(house.id, startDate, endDate))) {
	  alert('The dates chosen are not valid')
	  return
	}

	try {...

See the code on GitHub

Next part: Adding Stripe for payments

Want to become a better Web Developer? Join the 2022 Web Development Bootcamp!

⭐️⭐️⭐️ Join the 2022 Web Development Bootcamp ⭐️⭐️⭐️