userSlice.js:22 Uncaught (in promise) TypeError: Cannot create
property ‘error’ on string ‘User created successfully!’ at
signInFailure (userSlice.js:22:19) at
@reduxjs_toolkit.js?v=69e8a274:1773:26
Here is my reducer for making requests to API in my MERN application. I’m now encountering issues in Redux-Toolkit slice reducer function.
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
currentUser: null,
error: null,
loading: false,
};
const userSlice = createSlice({
name: "user",
initialState,
reducers: {
signInStart: (state) => {
state.loading = true;
},
signInSuccess: (state, action) => {
state.currentUser = action.payload;
state.loading = false;
state.error = null;
},
signInFailure: (state, action) => {
state.error = action.payload; // Handle both object and string payloads
state.loading = false;
},
});
export const {
signInStart,
signInSuccess,
signInFailure,
signOutUserStart,
} = userSlice.actions;
export default userSlice.reducer;
I tried to make the payload is string but it not solve the problem!
signInFailure: (state, action) => {
state.error = typeof action.payload === 'string'
? action.payload
: 'An error occurred';
state.loading = false;
1
Actually, signInFailure
action is being passed a string instead of an object and that causes the attempt to create a property error
on the string to fail.
Update the signInFailure
reducer to this:
signInFailure: (state, action) => {
if (typeof action.payload === 'string') {
state.error = action.payload;
} else if (action.payload && typeof action.payload.message === 'string') {
state.error = action.payload.message;
} else {
state.error = 'An error occurred';
}
state.loading = false;
}
Updated slice:
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
currentUser: null,
error: null,
loading: false,
};
const userSlice = createSlice({
name: "user",
initialState,
reducers: {
signInStart: (state) => {
state.loading = true;
},
signInSuccess: (state, action) => {
state.currentUser = action.payload;
state.loading = false;
state.error = null;
},
signInFailure: (state, action) => {
if (typeof action.payload === 'string') {
state.error = action.payload;
} else if (action.payload && typeof action.payload.message === 'string') {
state.error = action.payload.message;
} else {
state.error = 'An error occurred';
}
state.loading = false;
},
},
});
export const {
signInStart,
signInSuccess,
signInFailure,
} = userSlice.actions;
export default userSlice.reducer;
0