1

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

  • Sounds like you want to store the new `user`, not the old `userState`? See also [why the `useState` set method is not reflecting a change immediately](https://stackoverflow.com/q/54069253/1048572) - same problem, redux doesn't change anything. – Bergi Nov 30 '22 at 21:16

1 Answers1

0

Actually, you are storing current state in local storage, you have to store fetched user

const { user } = await dispatch(signIn({ email, password }));
localStorage.setItem('currentUser', user);

Or you can store user directly in createAsync function

You can unwrap and then store

const onClick = () => {
  dispatch(fetchUserById(userId))
    .unwrap()
    .then((originalPromiseResult) => {
      localStorage.setItem('currentUser', JSON.stringify(originalPromiseResult));
    })
    .catch((rejectedValueOrSerializedError) => {
      // handle error here
    })
}