I've set up a redux userSlice to retrieve 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;
The user data is successfully logged out 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);
displays 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'm encountering an error on state.user = action.payload
stating
Property 'user' does not exist on type 'WritableDraft<{ profile: { ipAddress: string; }; }>'
The defined user types are as follows:
client/src/interfaces/user.ts
export type User = {
profile: UserProfile
}
export type UserProfile = {
ipAddress: string
}
export type UserState = {
user: User
}
My redux state only shows the initial state being fulfilled, without the user's ipAddress as expected.