Reputation: 53
I am working on an app using react and redux but the redux state is showing null[Object object]. I have tried troubleshooting it but I dont know where the problem is coming from.
userSlice.js
import { createSlice } from '@reduxjs/toolkit';
export const userSlice = createSlice({
name: 'user',
initialState: {
user: null,
},
reducers: {
login: (state, action) => {
state.user += action.payload;
},
logout: (state) => {
state.user = null;
}
},
});
export const { logout, login } = userSlice.actions;
export const selectUser = (state) => state.user.user;
export default userSlice.reducer;
store.js
import { configureStore } from '@reduxjs/toolkit';
import userReducer from '../features/userSlice';
import appReducer from '../features/appSlice';
export default configureStore({
reducer: {
user: userReducer,
app: appReducer
},
});
App.js
useEffect(() => {
auth.onAuthStateChanged((authUser) => {
console.log(authUser.email);
if (authUser) {
dispatch(
login({
uid: authUser.uid,
photo: authUser.photoURL,
email: authUser.email,
displayName: authUser.displayName
})
)
} else {
dispatch(
logout()
)
}
})
}, [dispatch]);
Upvotes: 0
Views: 1854
Reputation: 202686
It seems the issue is that you incorrectly update your user
state upon successful authentication. You are doing some sort of concatenation in your login
reducer.
login: (state, action) => {
state.user += action.payload;
}
The state.user
initial value is null
and you add an object to it.
const state = {
user: null,
};
const action = {
payload: {
uid: 'authUser.uid',
photo: 'authUser.photoURL',
email: 'authUser.email',
displayName: 'authUser.displayName',
},
};
state.user += action.payload;
console.log(state.user);
If your goal is for "The result after authentication is that it should dispatch login function and fill in the state with the new values from firebase" then I think you want to replace the current state.user
value in the reducer.
login: (state, action) => {
state.user = action.payload;
}
const state = {
user: null,
};
const action = {
payload: {
uid: 'authUser.uid',
photo: 'authUser.photoURL',
email: 'authUser.email',
displayName: 'authUser.displayName',
},
};
state.user = action.payload;
console.log(state.user);
Upvotes: 2