import React, { useState, useEffect } from 'react';
import axios from 'axios'
import { Button, Form, Container, Navbar, Spinner, Alert } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors'
import { Link, Redirect } from 'react-router-dom'
import { handleLogin } from '../utils/auth'
const INIT_USER = {
email: '',
password: '',
}
function LogIn() {
const [validated, setValidated] = useState(false);
const [user, setUser] = useState(INIT_USER)
//로딩, 에러, diserved 상태 넣어야됨.
const [disabled, setDisabled] = useState(true)
const [error, setError] = useState('')
const [success, setSucces] = useState(false)
const [loading, setLoading] = useState(false)
useEffect(() => {
const isUser = Object.values(user).every(el => Boolean(el))
//Boolean : 참거짓 판별
//every : every뒤에 함수값이 return하는 값이 모두 참일때만 true출력 -> element가 하나도 빈 문자열이 존재하지 않을때
//empty string때만 false로 나옴.
isUser ? setDisabled(false) : setDisabled(true)
}, [user])
function handleChange(event) {
const { name, value } = event.target
// console.log(name, value)
setUser({ ...user, [name]: value })
}
async function handleSubmit(event) {
event.preventDefault()
// const form = event.currentTarget;
// if (form.checkValidity() === false) {
// event.preventDefault();
// event.stopPropagation();
// }
// setValidated(true);
try {
setLoading(true)
setError('')
await axios.post('/auth/login', user)
// 알아서 stringify하기 때문에 따로 해줄 필요 없음.
handleLogin(user)
setSucces(true)
} catch (error) {
catchErrors(error, setError)
//setError(error.response.data)
//error객체가 들어감.
} finally {
setLoading(false)
}
//server쪽에서 json형식으로 보낼것임
}
//success시 링크이동
if (success) {
console.log('success', success)
alert('로그인 되었습니다!')
return