Redux toolkit fullfilled even there is an error and showing the error message from django showing in fullfilled case
Fullfilled and update the state perfectly. But When use wrong credential, the detailed error from django showing in the fullfilled "userInfo" state. If we catch the error through rejectWithValue, the message is just "code 401"
userSlice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
export const login = createAsyncThunk(
"USER_LOGIN_REQUEST",
async (cred, thunkAPI) => {
try {
console.log("this is one thig");
console.log("username: ", cred.username, "password: ", cred.password);
const config = {
headers: {
"Content-type": "application/json",
},
};
const { data } = await axios.post(
"/api/users/login/",
{ username: cred.username, password: cred.password },
config
);
localStorage.setItem("userInfo", JSON.stringify(data));
return data;
} catch (error) {
return thunkAPI.rejectWithValue(error);
}
}
);
const userInfoFromStorage = localStorage.getItem("userInfo")
? JSON.parse(localStorage.getItem("userInfo"))
: null;
const initialState = {
userLogin: { userInfo: userInfoFromStorage },
};
const userSlice = createSlice({
name: "userRegister",
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(login.pending, (state = {}, action) => {
return { loading: true, userInfo: [] };
})
.addCase(login.fulfilled, (state = {}, action) => {
return { loading: false, userInfo: action.payload };
})
.addCase(login.rejected, (state = {}, action) => {
return { loading: false, error: action.payload.message };
});
},
});
export default userSlice.reducer;
store.js
const store = configureStore({
reducer: {
userLogin: userLoginReducer,
cart: cartReducer,
productList: productListReducer,
productDetails: productDetailsReducer,
},
// initialState,
middleware,
});
login.jsx
const { error, loading, userInfo } = userLogin;
const submitHandler = (e) => {
e.preventDefault();
dispatch(login({ username: email, password }));
};
I was expected error message form django on rejected case not in fullfilled case.