Reputation: 1
I am creating a login and in the .then function, setting the state of user. The data is set correctly but after redirect (through code) to the next page, I could not access the new state using useSelector function.
Login.js
const handleSubmit = useCallback((e) => {
async function getUser(){
return await login(username, password);
}
e.preventDefault();
getUser()
.then((userObj) => {
if(userObj.user._id !== undefined){
dispatch(setAuthUser(userObj.user));
message.current.innerHTML = '';
window.location = `/Shops/Near/`;
history.push('/Shops/Near/');
}
else{
message.current.innerHTML = 'Invalid username or password, try again!';
}
});
}, [username, password]);
Shops.js
import { useSelector } from 'react-redux';
const Shops = () => {
const [shops, setShops] = useState([]);
const [isPreferedPage, setIsPreferedPage] = useState(false);
const message = useRef(null);
const user = useSelector((state) => {
console.log(state.user);
return state.user;
}); //bug
userSlice.js
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
};
export const user = createSlice({
name: 'user',
initialState,
reducers: {
setAuthUser: (state, action) => {
state = action.payload;
},
I want to know what is the problem, I tried to remove the async call and even set the state in empty call but still it never been updated.
Thanks
Upvotes: 0
Views: 3165
Reputation: 44078
You cannot do state =
as that would not modify the object in state
, but throw the object in state
away and put a new one into the variable.
state.foo =
would be okay, state =
is not.
Do return action.payload
instead.
See also https://redux-toolkit.js.org/usage/immer-reducers#resetting-and-replacing-state
Upvotes: 3