Airbnb clone, change state after we login

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.

We have a missing piece now. If we try to login, we are not immediately logged in - we must do a page reload, which is not nice.

Let’s login the user immediately after the login process is successful.

In components/LoginModal.js we need to import the useStoreActions object from easy-peasy:

import { useStoreActions } from 'easy-peasy'

then inside the LoginModal component we initialize setLoggedIn and setHideModal:

const setLoggedIn = useStoreActions((actions) => actions.login.setLoggedIn)
const setHideModal = useStoreActions((actions) => actions.modals.setHideModal)

Then we call them inside the submit() function after we get a response:

const submit = async () => {
  const response = await axios.post('/api/auth/login', {
    email,
    password
  })

  if (response.data.status === 'error') {
    alert(response.data.message)
    return
  }

  setLoggedIn(true)
  setHideModal(true)
}

Here is the full component source code:

import { useState } from 'react'
import axios from 'axios'
import { useStoreActions } from 'easy-peasy'

export default function LoginModal(props) {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  const setLoggedIn = useStoreActions((actions) => actions.login.setLoggedIn)
  const setHideModal = useStoreActions((actions) => actions.modals.setHideModal)

  const submit = async () => {
    const response = await axios.post('/api/auth/login', {
      email,
      password
    })

    if (response.data.status === 'error') {
      alert(response.data.message)
      return
    }

    setLoggedIn(true)
    setHideModal(true)
  }

  return (
    <>
      <h2>Log in</h2>
      <div>
        <form
          onSubmit={(event) => {
            submit()
            event.preventDefault()
          }}
        >
          <input
            id="email"
            type="email"
            placeholder="Email address"
            onChange={(event) => setEmail(event.target.value)}
          />
          <input
            id="password"
            type="password"
            placeholder="Password"
            onChange={(event) => setPassword(event.target.value)}
          />
          <button>Log in</button>
        </form>
      </div>
      <p>
        Don't have an account yet?{' '}
        <a href="javascript:;" onClick={() => props.showSignup()}>
          Sign up
        </a>
      </p>
    </>
  )
}

See the code on GitHub

Next part: Log in after registration

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

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