0

I'm trying to update my notification but I always get the previous state for example my initialState = {message: null, type: "}

but if I login the state changes and the notification has to be displayed is "login succesful" the redux dev tools show that the initial state has not changed

but if I update the state again for example I provide a new notificaiton ("hello") the state shows {message: "logged in ", type:"success"} instead of {message: "hello"}

this is what my notificationReducer.js looks like

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

const notificationSlice = createSlice({
  name: "notification",
  initialState: {
    type: "",
    message: null,
  },
  reducers: {
    setNotification(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  extraReducers: (builder) => {
    builder.addCase(updateNotificationAsync.fulfilled, (state) => {
      // This case can be left empty since the notification state update
      // is already handled in the updateNotificationAsync action creator
    });
  },
});

export const { setNotification } = notificationSlice.actions;

// using createAsyncThunk
export const updateNotificationAsync = createAsyncThunk(
  "notification/updateNotificationAsync",
  async ({ message, type, time }, { dispatch }) => {
    dispatch(setNotification({ message, type }));

    return new Promise((resolve) => {
      setTimeout(() => {
        dispatch(setNotification({ message: null, type: "" }));
        resolve();
      }, time * 1000);
    });
  }
);
// using redux thunks
export const updateNotification = (message, type, time) => {
  return async (dispatch) => {
    console.log(message);
    dispatch(setNotification({ message, type }));
    setTimeout(() => {
      dispatch(setNotification({ message: null, type: "" }));
    }, time * 1000);
  };
};

export default notificationSlice.reducer;

As you can see from the code I tried using createAsyncThunk and the normal redux thunk but it doesn't have any effect they both get me the same result so maybe I'm thinking it's the setNotificaton that is the problem. so if anyone can help me out it would be much appreciated.

also I have a userReducer which is giving me the accurate state updates everytime so that is why I said maybe it's the setNotification

Athulkal
  • 23
  • 4
  • does this [answer](https://stackoverflow.com/questions/35411423/how-to-dispatch-a-redux-action-with-a-timeout) help? – Yaman Abd Aug 20 '23 at 07:18

0 Answers0