dispatch에 then을 사용하고 싶습니다.
1001
작성한 질문수 1
리덕스 툴킷을 사용하면서
dispatch().then()을 하면 then of undefined 에러가 나더라구요.
https://redux-toolkit.js.org/api/createAsyncThunk#handling-thunk-results
공식 홈페이지 예제를 보고도 따라해보았는데 예제에 있는 방법들 모두 에러가 났습니다.
리턴을 return response.data;로 한 것이 문제였나 (프로미즈를 리턴하지 않고) 싶었지만
공식홈페이지 예제에서도 createAsyncThunc에서 return response.data 를 한 액션에 then()을 사용하더라고요.
어디가 문제였을까요! 제가 따라한 코드를 첨부합니다.
//store.js
import {configureStore, getDefaultMiddleware} from '@reduxjs/toolkit';
import reducer from './data_reducers/rootReducer';
const firstMiddleWare = (store) => (dispatch) => (action) => {
dispatch(action);
};
const store = configureStore({
reducer,
middleware: [firstMiddleWare, ...getDefaultMiddleware({serializableCheck: false})],
devTools: process.env.NODE_ENV !== 'production',
});
export default store;
//axios.js
import axios from '@/axios';
import {BASEURL} from '@/App';
import {authToken} from '@/service/auth/auth.service';
import {createAsyncThunk} from '@reduxjs/toolkit';
export const fetchUserById = createAsyncThunk('users/fetchByIdStatus', async (userId, thunkAPI) => {
let response = await axios.get(`${BASEURL}/test/`, {
headers: {
Authorization: 'Bearer ' + authToken(),
'Content-Type': 'application/json',
},
});
return response.data;
});
//reducer.js
import {
fetchUserById,
} from '@/data_actions/userInfo_action/userInfo_action';
import {createSlice} from '@reduxjs/toolkit';
import {fetchUserById} from '@/data_actions/userInfo_action/userInfo_action';
const initialState = {
isLogging: true,
profile: null,
isError: false,
status: '',
errorStatus: {},
};
export const userInfoSlice = createSlice({
name: 'userInfo',
initialState,
reducers: {
resetStatus(state, action) {
state.status = '';
state.errorStatus = {};
},
},
extraReducers: (builder) => {
builder.addCase(fetchUserById.fulfilled, (state, action) => {});
},
});
//component
import React, {useEffect, useRef, useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {unwrapResult} from '@reduxjs/toolkit';
function MyAccount(props) {
const dispatch = useDispatch();
const onClickk = async () => {
dispatch(fetchUserById())
.then(unwrapResult)
.then((res) => {
console.log(res);
})
.catch((error) => {});
};
return (
<button onClick={onClickk}>test</button>
);
}
답변 1
context api, redux를 혼용하는건 별로일까요?
0
376
1
섹션 3 mobx autorun 관련 질문입니다.
0
263
1
thunk 미들웨어 잡업 중 논리로직 단계? 질문이 있습니다.
0
298
1
rootSaga에서 call를 사용하는 이유가 궁금합니다.
0
363
1
observable의 함수를 익명함수로 바꿔봤습니다.
0
393
1
useSelector 리랜더링 질문있습니다.
0
385
1
비동기 action 타입을 뭘로 지정해야 할까요?
0
260
1
redux-thunk질문
0
435
1
state 변경 시 질문
0
351
1
state변경 시 질문
0
333
2
firstMiddleware와 thunkMiddleware 순서 질문
0
438
1
객체 동적 다이나믹 속성?? 질문
1
278
1
미들웨어 질문
0
254
1
리덕스 사가 실습 파일 확인 부탁드립니다!
1
587
2
1-6 강의에서 질문 있습니다!
1
365
1
redux-saga 깃헙 파일
0
376
1
createStore -> configureStore
0
303
1
전역 변수와 전역 상태 값
0
672
2
Redux toolkit 과 axios API 호출에 관한 질문입니다.
0
442
1
MobX Data
0
235
1
mobx state action 변화 감지 관련
0
726
1
mobx configure
0
216
1
리덕스 툴킷 과 saga질문
0
295
1
로깅 미들웨어 질문입니다
0
241
1





