I followed redux toolkit docs here to use 'then()'.
https://redux-toolkit.js.org/api/createAsyncThunk#handling-thunk-results
and I wrote exactly the same codes in my app.
and I get Cannot read property 'then' of undefined error.
I tried other ways to achieve it, include using .unwrap() (I got unwrap of undefined error),
async-await (I got 'meta' of undefined) etc..
but all of them failed.
What I did wrong?
- action.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
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>
);
}
- 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;