Reputation: 992
I am using a redux slice in a react project to store information about the current user. However, I am getting the following error when loading the page:
TypeError: Cannot read properties of undefined (reading 'name')
Dashboard.js:
export function Dashboard() {
const currentUser = useSelector(state => state.currentUser);
const dispatch = useDispatch();
return (
<div>
<p>{currentUser.name}</p>
<p>{currentUser.description}</p>
</div>
<Button onClick={() => dispatch(setCurrentUser(name, description))}>Set user</Button>
);
}
currentUserSlice.js:
import { createSlice } from '@reduxjs/toolkit'
export const currentUser = createSlice({
name: 'currentUser',
initialState: {
name: "",
description: ""
},
reducers: {
setCurrentUser: (state, action) => {
return state = {
name: action.payload.name,
description: action.payload.description
}
}
}
})
// each case under reducers becomes an action
export const { setCurrentUser } = currentUserSlice.actions
export default currentUserSlice.reducer
store.js:
import { configureStore } from '@reduxjs/toolkit'
import currentUserReducer from './currentUserSlice'
export default configureStore({
reducer: {
currentUser: currentUserReducer,
}
})
Update I did not properly import the reducer into store.js. However, the dispatch is not updating the data now that I have imported it
Upvotes: 2
Views: 2966
Reputation: 1054
You are sending two values in your payload instead of an object. Please update your dispatched function to send an object instead:
export function Dashboard() {
const currentUser = useSelector(state => state.currentUser);
const dispatch = useDispatch();
return (
<div>
<p>{currentUser.name}</p>
<p>{currentUser.description}</p>
</div>
<Button onClick={() => dispatch(setCurrentUser({name, description}))}>Set user</Button>
);
}
Upvotes: 1