everyone! I’m trying to create a Redux toolkit slice using an async thunk for a user’s login. I’m following the official documentation to achieve that, using the ‘creator callback‘ notation (see link: The reducers “creator callback” notation), but the docs have nothing to do with the library.
Here’s what I tried:
// src/redux/features/user/userSlice.js
import { createAppSlice } from '@/redux/utils/createAppSlice';
...
export const authSlice = createAppSlice({
name: 'auth',
initialState,
reducers: (create) => ({
loginUser: create.asyncThunk(
async (values, thunkApi) => {
try {
const config = {
headers: {
'Content-Type': 'application/json',
},
};
const { data } = await axios.post(`${BASE_URL}/user/login`, values, config);
localStorage.setItem('token', data.access_token);
return data;
} catch (error) {
if (error.response && error.response.data.message) {
return rejectWithValue(error.response.data.message);
} else {
return rejectWithValue(error.message);
}
}
},
{
pending: (state) => {
state.loading = true;
state.error = null;
},
rejected: (state, action) => {
state.loading = false;
state.error = payload;
},
fulfilled: (state, action) => {
state.loading = false;
state.token = payload.access_token;
},
}
),
)},
)};
The docs recommend a ‘special’ setup create.asyncThunk:
To avoid pulling
createAsyncThunk
into the bundle size ofcreateSlice
by default, some extra setup is required to usecreate.asyncThunk
.The version of
createSlice
exported from RTK will throw an error ifcreate.asyncThunk
is called.Instead, import
buildCreateSlice
andasyncThunkCreator
, and create your own version of createSlice.
I created that special createAppSlice
and imported it, as you can see in the code above.
// src/redux/utils/createAppSlice.js
import { buildCreateSlice, asyncThunkCreator } from '@reduxjs/toolkit'
export const createAppSlice = buildCreateSlice({
creators: { asyncThunk: asyncThunkCreator },
})
But it didn’t work, since none of these two functions are exported members of '@reduxjs/toolkit'
. I’m getting this error: TypeError: (0 , _reduxjs_toolkit__WEBPACK_IMPORTED_MODULE_0__.buildCreateSlice) is not a function
Has anyone ever found the same problem? Is there a way to solve this following the docs recommendation? Thank you!
NOTE: I didn’t use the extraReducers option because the library marks it as deprecated.
Ezequiel Angélico is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.