작성
·
463
0
안녕하세요 !
강의 잘 듣고 있습니다.
아래처럼 작성했는데 로그인 성공했는데 workspace로 가지지 않아서요.
console.log(data) 찍어보니
데이터가 들어왔다가 초기화 돼버리는데
그래서 이동이 안되는 것 같은데 원인을 잘 모르겠습니다.ㅜㅜ
pages_channel_index_tsx 어쩌고가 response에 뜨는데 혹시 연관있을까 해서 첨부합니다..
dimport useInput from '@hooks/useInput';
import React, { useCallback, useState } from 'react';
import { Header, Button, Error, Form, Input, Label, LinkContainer, Success } from '@pages/signup/styles';
import { Link, Navigate } from 'react-router-dom';
import axios from 'axios';
import useSWR from 'swr';
import fetcher from '@utils/fetcher';
const LogIn = () => {
const { data, error, mutate } = useSWR('/api/users', fetcher);
const [logInError, setLogInError] = useState(false);
const [email, onChangeEmail] = useInput('');
const [password, onChangePassword] = useInput('');
const onSubmit = useCallback(
(e) => {
e.preventDefault();
setLogInError(false);
axios
.post(
'/api/users/login',
{ email, password },
{
withCredentials: true,
}, //get일때와 post일때 withCredentials 위치가 다르다.
)
.then((response) => {
mutate(response.data);
})
.catch((error) => {
setLogInError(error.response?.data?.statusCode === 401);
});
},
[email, password],
);
console.log(data, '데이타');
if (data) {
return <Navigate to="/workspace/channel" />;
}
return (
<div id="container">
<Header>Sleact</Header>
<Form onSubmit={onSubmit}>
<Label id="email-label">
<span>이메일 주소</span>
<div>
<Input type="email" id="email" name="email" value={email} onChange={onChangeEmail} />
</div>
</Label>
<Label id="password-label">
<span>비밀번호</span>
<div>
<Input type="password" id="password" name="password" value={password} onChange={onChangePassword} />
</div>
{logInError && <Error>이메일과 비밀번호 조합이 일치하지 않습니다.</Error>}
</Label>
<Button type="submit">로그인</Button>
</Form>
<LinkContainer>
아직 회원이 아니신가요?
<Link to="/signup">회원가입 하러가기</Link>
</LinkContainer>
</div>
);
};
export default LogIn;
import fetcher from '@utils/fetcher';
import axios from 'axios';
import React, { FC, useCallback } from 'react';
import { Navigate } from 'react-router-dom';
import useSWR from 'swr';
const Workspace: FC = ({ children }) => {
const { data, error, mutate } = useSWR('/api/users', fetcher);
const onLogout = useCallback(() => {
axios
.post('/api/users/logout', null, {
withCredentials: true,
})
.then((res) => {
mutate(res.data);
});
}, []);
if (!data) {
return <Navigate to="/login" />;
}
return (
<div>
<button onClick={onLogout}>로그아웃</button>
{children}
</div>
);
};
export default Workspace;
답변 2
0
ㅇㅇlogin에서 onSubmit 안쪽과 바깥쪽에 ,
fetcher에 콘솔을 추가하여 실행해봤습니다.
import axios from 'axios';
const fetcher = (url: string) => {
axios
.get(url, {
withCredentials: true,
// withCredentials: true, proxy를 안써서 백엔드, 프론트 포트가 다르면 쿠키를 전달할 수 없음. 로그인이 됐는지 확인불가. 그래서 이거로 해결.
})
.then((response) => console.log(response.data, '응답'));
};
export default fetcher;
import useInput from '@hooks/useInput';
import React, { useCallback, useState } from 'react';
import { Header, Button, Error, Form, Input, Label, LinkContainer, Success } from '@pages/signup/styles';
import { Link, Navigate } from 'react-router-dom';
import axios from 'axios';
import useSWR from 'swr';
import fetcher from '@utils/fetcher';
const LogIn = () => {
const { data, error, mutate } = useSWR('/api/users', fetcher);
const [logInError, setLogInError] = useState(false);
const [email, onChangeEmail] = useInput('');
const [password, onChangePassword] = useInput('');
const onSubmit = useCallback(
(e) => {
e.preventDefault();
setLogInError(false);
axios
.post(
'/api/users/login',
{ email, password },
{
withCredentials: true,
}, //get일때와 post일때 withCredentials 위치가 다르다.
)
.then((response) => {
console.log(response.data, 'onSubmit안에서');
mutate(response.data);
})
.catch((error) => {
setLogInError(error.response?.data?.statusCode === 401);
});
},
[email, password],
);
console.log(data, 'login컴포에서');
if (data) {
return <Navigate to="/workspace/channel" />;
}
return (
<div id="container">
<Header>Sleact</Header>
<Form onSubmit={onSubmit}>
<Label id="email-label">
<span>이메일 주소</span>
<div>
<Input type="email" id="email" name="email" value={email} onChange={onChangeEmail} />
</div>
</Label>
<Label id="password-label">
<span>비밀번호</span>
<div>
<Input type="password" id="password" name="password" value={password} onChange={onChangePassword} />
</div>
{logInError && <Error>이메일과 비밀번호 조합이 일치하지 않습니다.</Error>}
</Label>
<Button type="submit">로그인</Button>
</Form>
<LinkContainer>
아직 회원이 아니신가요?
<Link to="/signup">회원가입 하러가기</Link>
</LinkContainer>
</div>
);
};
export default LogIn;
import fetcher from '@utils/fetcher';
import axios from 'axios';
import React, { FC, useCallback } from 'react';
import { Navigate } from 'react-router-dom';
import useSWR from 'swr';
const Workspace: FC = ({ children }) => {
const { data, error, mutate } = useSWR('/api/users', fetcher);
const onLogout = useCallback(() => {
axios
.post('/api/users/logout', null, {
withCredentials: true,
})
.then((res) => {
mutate(res.data);
});
}, []);
if (!data) {
return <Navigate to="/login" />;
}
return (
<div>
<button onClick={onLogout}>로그아웃</button>
{children}
</div>
);
};
export default Workspace;
새로고침 하면 fetcher가 작동되면서는 데이터가 찍히는데
로그인 컴포넌트에서 useSWR의 data가 계속 초기화가 되는 것 같은데..
계속 고민해보겠습니다.. ㅠ뭘까요..
다른 댓글 보니까 조건을 data===false 로 해보라고 하신거 보고 해보니
이런 타입에러가 뜨네요...ㅠㅠ
0
@utils/fetcher 한 번 보여주시고
console.log(response.data, '응답') 한 번 찍어보세요.
그리고 네트워크 탭에서 /api/user 요청에 대한 response가 로그인 후 항상 데이터가 들어있는지 확인해보세요.
fetcher에서 return 빼먹으셨습니다. 강좌에서 보시면 { } 가 아니라 ( ) 입니다.