I have a redux userSlice that is attempting to get user data from the store.
client/src/redux/features/userSlice.ts
import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { User } from "../../interfaces/user";
import userApi from "../../apis/user";
export const getUser = createAsyncThunk("user/getUser", async (_, thunkApi) => {
try {
const response = await userApi.getUser();
return response;
} catch (error) {
throw thunkApi.rejectWithValue({ error: "user not initialized" });
}
});
const userSlice = createSlice({
name: "user",
initialState: {
profile: {
ipAddress: "",
},
},
reducers: {
getUser: (state, action: PayloadAction<User>) => {
state.user = action.payload;
},
},
});
export const { getUser: getUserAction } = userSlice.actions;
export default userSlice.reducer;
I am able to successfully log out the user in the API interface:
client/src/apis/user.ts
const userApi = {
getUser: async () => {
try {
const response = await fetch("http://localhost:5000/user/:ipAddress");
const user = await response.json();
console.log("in user api:", user);
return user;
} catch (error) {
console.error("Error fetching user:", error);
return error;
}
},
};
export default userApi;
console.log("in user api:", user);
returns the following:
in user api:
Object { user: {…} }
user: Object { _id: "65c1f831b5759dc19442396d", ipAddress: "::ffff:127.0.0.1", createdAt: "2024-02-06T09:13:21.391Z", … }
<prototype>: Object { … }
However, I am seeing an error on state.user = action.payload
which states Property 'user' does not exist on type 'WritableDraft<{ profile: { ipAddress: string; }; }>'
The user types I've defined are as such:
client/src/interfaces/user.ts
export type User = {
profile: UserProfile
}
export type UserProfile = {
ipAddress: string
}
export type UserState = {
user: User
}
My redux state is showing only the initial state being fulfilled, but not the ipAddress of the user, as expected.
There is no user
property in the userSlice
state. The userSlice
state is a User
type. If getUser
is setting the "user" then it should replace the state. Return action.payload
since state = action.payload
is invalid, you can't reassign the draft state.
Example:
const initialState: User = {
profile: { ipAddress: "" },
};
const userSlice = createSlice({
name: "user",
initialState,
reducers: {
getUser: (state, action: PayloadAction<User>) => {
return action.payload; // <-- return User value
},
},
});