리덕스 툴킷에서 rejected 일 때 에러메세지 처리하기
안녕하세요 제로초님!
궁금한 게 있어서 질문 남깁니다!
로그인을 처리하는 로직에서 error 발생시 직접 정의한 에러 메시지를 보여주고 싶은데요..
툴킷을 사용하기 전에는 axios에 error.response를 통해서 직접 정의한 메세지를 뽑아 사용했었는데
rejected에서 action.error.message 를 담아도 원하는 값이 안나오네요
"존재하지 않는 이메일입니다!" 라는 문구를 logInError에 넣고싶습니다!
방법을 알 수 있을까요? 감사합니다!
혹시 몰라서 코드도 같이 올리겠습니다!
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { ResUserData } from 'api/user/types'
import { userLogin } from 'store/user/action'
interface UserState {
logInLoading: boolean
logInDone: boolean
logInError: string | null
user: ResUserData | null
}
const initialState: UserState = {
logInLoading: false,
logInDone: false,
logInError: null,
user: null
}
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {},
extraReducers: bulid =>
bulid
.addCase(userLogin.pending, (state: UserState) => {
state.logInLoading = true
state.logInDone = false
state.logInError = null
})
.addCase(
userLogin.fulfilled,
(state: UserState, action: PayloadAction<ResUserData>) => {
state.logInLoading = false
state.logInDone = true
state.user = action.payload
}
)
.addCase(userLogin.rejected, (state: UserState, action) => {
state.logInLoading = false
state.logInError = action.error.message!
})
})
export default userSlice.reducer
Câu trả lời 3
1
{
"name": "Error",
"message": "Request failed with status code 400",
"stack": "Error: Request failed with status code 400\n at createError (http://localhost:3000/static/js/vendors~main.chunk.js:4954:15)\n at settle (http://localhost:3000/static/js/vendors~main.chunk.js:5225:12)\n at XMLHttpRequest.onloadend (http://localhost:3000/static/js/vendors~main.chunk.js:4281:7)"
}
이렇게 출력이 됩니다.
0
서버에서는 400에러로 내려주는게 맞죠?
이게 await userLoginApi(payload)부분을 try catch로 감싸서 에러인 경우 catch의 error에서 에러메시지를 추출하고 다시 throw new Error('message')를 해서 reject에서 받으셔야 할 것 같습니다.
0
// ...
// validation
if (!name || !username || !password)
return res.status(400).json({ message: '빈 값이 존재합니다.' })
const exUser = await User.findOne({ username })
if (exUser) return res.status(400).json({ message: '이미 존재하는 아이디 입니다.' })
if (name.length < 3) return res.status(400).json({ message: '아이디는 3자 이상으로 해주세요.' })
if (password.length < 5)
return res.status(400).json({ message: '비밀번호를 5자 이상으로 해주세요.' })
// ...
네 로그인 API 에서 저런식으로 검사를 하고있습니다!
제로초님이 제안한 방식대로 한 번 해보겠습니다
답변 때문에 시간 내주셔서 감사합니다 :)
0
userLoginAPI 라는 axios 함수를 만들어서
action 파일에서 사용 중 입니다!
0
// ...
.addCase(userLogin.rejected, (state: UserState, action: any) => {
state.logInLoading = false
state.logInError = action.error.response.data.message
})
// ...
이렇게 해봤는데 안되는 거 같네요 ㅠㅠ
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'data')
context api, redux를 혼용하는건 별로일까요?
0
368
1
섹션 3 mobx autorun 관련 질문입니다.
0
255
1
thunk 미들웨어 잡업 중 논리로직 단계? 질문이 있습니다.
0
285
1
rootSaga에서 call를 사용하는 이유가 궁금합니다.
0
358
1
observable의 함수를 익명함수로 바꿔봤습니다.
0
383
1
useSelector 리랜더링 질문있습니다.
0
382
1
비동기 action 타입을 뭘로 지정해야 할까요?
0
258
1
redux-thunk질문
0
432
1
state 변경 시 질문
0
346
1
state변경 시 질문
0
329
2
firstMiddleware와 thunkMiddleware 순서 질문
0
433
1
객체 동적 다이나믹 속성?? 질문
1
272
1
미들웨어 질문
0
247
1
리덕스 사가 실습 파일 확인 부탁드립니다!
1
581
2
1-6 강의에서 질문 있습니다!
1
359
1
redux-saga 깃헙 파일
0
369
1
createStore -> configureStore
0
300
1
전역 변수와 전역 상태 값
0
666
2
Redux toolkit 과 axios API 호출에 관한 질문입니다.
0
439
1
MobX Data
0
233
1
mobx state action 변화 감지 관련
0
717
1
mobx configure
0
208
1
리덕스 툴킷 과 saga질문
0
287
1
로깅 미들웨어 질문입니다
0
238
1

