i have an async thunk function that gets a user from database and sets it to the state, but i want to set the user to local storage after getting it,
//SignIn.tsx
const userState = useAppSelector((state) => state.user);
const handleSignIn = async (e: React.SyntheticEvent) => {
e.preventDefault();
const user = await dispatch(signIn({ email, password }));
localStorage.setItem('currentUser', JSON.stringify(userState));
console.log(userState);
navigate('/shop');
};
//userSlice.ts
export const signIn = createAsyncThunk(
'user/signIn',
async ({ email, password }: { email: string; password: string }) => {
const { user }: UserCredential = await signInWithEmailAndPassword(
auth,
email,
password
);
const data = await getUser(user);
return { data, user };
}
);
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(signIn.fulfilled, (state, action) => {
state.email = action.payload.user.email;
state.token = action.payload.user.refreshToken;
state.id = action.payload.user.uid;
state.avatarUrl = action.payload.data.avatarUrl;
state.lastName = action.payload.data.lastName;
state.name = action.payload.data.name;
});
}
im awaiting the dispatch and then trying to set the user to local storage using updated state, idk why the state doesnt update after awaiting the dispatch, instead of updated state im setting the PREVIOUS state to the local storage, please help, im struggling with this for an hours