aboutsummaryrefslogtreecommitdiffstats
path: root/helpers/submitForm.js
blob: 631c17420832d5b9dc3958bc647cff88555b4a58 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import fetchJson from 'helpers/fetchJson'

const submitForm = async (e, url, mutateUser, setErrorMsg) => {
  e.preventDefault()

  const isRegister = url.includes('register')
  if (
    isRegister && e.currentTarget.password_confirm
      && e.currentTarget.password_confirm.value
      !== e.currentTarget.password.value
  ) {
    setErrorMsg('passwords_not_match')
    return
  } else {
    setErrorMsg()
  }

  const body = {
    email: e.currentTarget.email.value,
    password: e.currentTarget.password.value,
    ...(e.currentTarget.language
      ? {language: e.currentTarget.language.value}
      : {}
    ),
    ...(e.currentTarget.theme
      ? {theme: e.currentTarget.theme.value}
      : {}
    ),
  }

  try {
    mutateUser(
      await fetchJson(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
    )
  } catch (err) {
    setErrorMsg(isRegister ? 'register_error' : 'login_error')
  }
}

export default submitForm