Hello everyone, I am writing crud-operations using redux-toolkit and typescript. I have a component UserInfo , where I map through user - and all users are displayed on the homepage. I have a childComponent named userDisplay, where the particular user is displayed. There I update the data and that works. But when I go back to /home, I have a blank site and the error:
user.map is not a function
I logged the typeof user in the UserInfo and it gives me back ‘object’. So, when it is an object, I cannot use map(). But why this map is working, when I call the homepage and after updating it works not anymore.
userInfo:
const UserInfo = () => {
const dispatch = useAppDispatch();
const selector = useAppSelector((state:RootState)=>state.user);
const {user} = selector;
console.log(typeof user); //gives back object
useEffect(()=>{
dispatch(getAllUser())
}, [dispatch])
return (
<Container>
<Title>Neue Benutzer</Title>
<ContentWrapper>
{user.map((item)=>(
<div key={item._id}>
Userslice update:
type AsyncThunkConfig = {
state: RootState
}
export const updateUser = createAsyncThunk<User[], UpdateData, AsyncThunkConfig>('/user/update', async (updateData, thunkAPI)=>{
try{
const token:string = thunkAPI.getState().auth.user!.accessToken;
return await userService.updateUser(updateData, token);
}catch (error:any) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString()
return thunkAPI.rejectWithValue(message as string)
}
});
userSlice getAll:
export const getAllUser = createAsyncThunk<User[], void, AsyncThunkConfig>('/user/findAll', async (_, thunkAPI)=>{
try{
const token = thunkAPI.getState().auth.user!.accessToken;
return await userService.getAllUser(token);
}catch (error:any) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString()
return thunkAPI.rejectWithValue(message as string)
}
})
The http.Request works, so perhaps the error is in my backend
update:
userRouter.put('/:id', verifyTokenAndAuthorization, async (req:Request, res:Response)=>{
try{
const updatedUser = await User.findByIdAndUpdate(req.params.id,{
$set: req.body,
},{new:true})
res.status(200).json(updatedUser);
} catch(error){
res.status(404)
throw new Error("User not found");
}
});
getAll:
userRouter.get('/find', verifyTokenAndAdmin, async (req:Request, res:Response)=>{
try{
const allUsers = await User.find();
res.status(200).json(allUsers);
console.log(typeof allUsers); //gives back object, object (I have two users in the database)
} catch(error){
res.status(404).json("Users not found");
}
});
Thanks for your help.