Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Week/#21] 8주차 워크북 미션 #22

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions week3/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions week3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
},
"dependencies": {
"@hookform/resolvers": "^3.9.1",
"@tanstack/react-query": "^5.61.0",
"@tanstack/react-query-devtools": "^5.61.0",
"axios": "^1.7.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
Expand Down
59 changes: 56 additions & 3 deletions week3/src/components/navbar.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import axios from "axios";
import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query"
import styled from "styled-components";

const NavContainer = styled.div`
Expand All @@ -15,6 +17,12 @@ const HomeContainer = styled.div`

const LoginContainer = styled.div`
flex-shrink: 0;

span {
color: white;
margin: auto 10px;
font-weight: bold;
}
`;

const HomeLink = styled(Link)`
Expand All @@ -23,6 +31,13 @@ const HomeLink = styled(Link)`
font-weight: 500;
color: #ea345c;
`;

const LogoutBtn = styled.button`
background: transparent;
color: white;
border: none;
`;

const LoginLink = styled(Link)`
text-decoration: none;
color: white;
Expand All @@ -45,18 +60,56 @@ const BtnLink = styled(Link)`
`;

const Navbar = () => {

const getUser = async () => {
const accessToken = localStorage.getItem("accessToken");

if (!accessToken) {
console.log("유저 정보 가져오기 실패:");
}

const response = await axios.get('http://localhost:3000/user/me', {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
console.log(response.data);
return response.data;
}

const { data } = useQuery({
queryFn: () => getUser(),
queryKey: ['user'],
});

const userName = data?.email?.split('@')[0];

return (
<NavContainer>
<HomeContainer>
<HomeLink to={'/'}>WATCHA</HomeLink>
</HomeContainer>

<LoginContainer>
<LoginLink to='/login'>로그인</LoginLink>
<BtnLink to='/signup'>회원가입</BtnLink>
{userName ? (
<>
<span>{userName}님 환영합니다</span>
<LogoutBtn
onClick={() => {
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");
}}
>로그아웃</LogoutBtn>
</>
) : (
<>
<LoginLink to='/login'>로그인</LoginLink>
<BtnLink to='/signup'>회원가입</BtnLink>
</>
)}
</LoginContainer>
</NavContainer>
);
};

export default Navbar;
export default Navbar;
10 changes: 9 additions & 1 deletion week3/src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'

export const queryClient = new QueryClient();

createRoot(document.getElementById('root')).render(
<App />
<QueryClientProvider client={queryClient}>
<App />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>

)
130 changes: 84 additions & 46 deletions week3/src/pages/login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,48 +2,14 @@ import { useForm } from "react-hook-form";
import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import styled from 'styled-components'

const LoginContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
margin-top: 10vh;

h1 {
margin: 5vh auto;
}
`;

const Input = styled.input`
width: 20vw;
height: 5vh;
border: 0;
padding: 0;
padding-left: 10px;
border-radius: 10px;
box-sizing: border-box;
`;

const Error = styled.p`
color: red;
`;

const Button = styled.button`
background-color: ${({ isValid }) => (isValid ? '#ea345c' : '#d3d3d3')};
color: white;
width: 20vw;
height: 5vh;
border: 0;
padding: 0;
border-radius: 10px;

&:disabled {
background-color: #d3d3d3;
}
`;
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { useMutation } from "@tanstack/react-query"

const Login = () => {

const navigate = useNavigate();

const schema = yup.object().shape({
email: yup
.string()
Expand All @@ -56,13 +22,44 @@ const Login = () => {
.required(),
})

const { register, handleSubmit, formState: { errors, isValid }, trigger } = useForm({
const { register, handleSubmit, formState: { errors }, trigger } = useForm({
resolver: yupResolver(schema),
mode: "onChange"
});

const onSubmit = (data) => {
console.log(data);
const loginPost = async ({ email, password }) => {
const response = await axios.post('http://localhost:3000/auth/login', {
email,
password,
});

return response;
}

const { mutate } = useMutation({
mutationFn: loginPost,
mutationKey: ['login'],
onSuccess: (response) => {
console.log("로그인 성공", response.data);
const { accessToken, refreshToken } = response.data;

if (response.status === 201) {
localStorage.setItem("accessToken", accessToken);
localStorage.setItem("refreshToken", refreshToken);
}
navigate("/");
},
onError: (error) => {
console.log("로그인 실패", error)
}
});

const onSubmit = async (data) => {
try {
mutate({ email: data.email, password: data.password });
} catch(err) {
console.log(err)
}
}

return(
Expand All @@ -85,13 +82,54 @@ const Login = () => {
/>
<Error>{errors.password?.message}</Error>
<Button
type="submit"
isValid={isValid}
disabled={!isValid}>로그인</Button>
type="submit"
// isValid={isValid}
// disabled={!isValid}
>로그인</Button>
</form>
</>
</LoginContainer>
);
}

export default Login;
export default Login;

const LoginContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
margin-top: 10vh;

h1 {
margin: 5vh auto;
}
`;

const Input = styled.input`
width: 20vw;
height: 5vh;
border: 0;
padding: 0;
padding-left: 10px;
border-radius: 10px;
box-sizing: border-box;
`;

const Error = styled.p`
color: red;
`;

const Button = styled.button`
background-color: #ea345c;
color: white;
width: 20vw;
height: 5vh;
border: 0;
padding: 0;
border-radius: 10px;

// &:disabled {
// background-color: #d3d3d3;
// }

`;
Loading