0

I have a simple reducer function

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { TSnackBarProps } from 'plugins/notification/NotificationContext';
import { MAX_STACK } from 'plugins/notification/NotificationsStack';

interface INotificationState {
  notifications: TSnackBarProps[];
}

const initialState: INotificationState = {
  notifications: [],
};

const notificationSlice = createSlice({
  name: 'notification',
  initialState,
  reducers: {
    addNewNotification(state, action: PayloadAction<TSnackBarProps>) {
      const { notifications } = state;
      const { payload: notification } = action;
      if (notifications.find((n) => n.severity === notification.severity && n.key === notification.key)) {
        return;
      }
      if (notifications.length >= MAX_STACK) {
        notifications.splice(0, notifications.length - MAX_STACK);
      }

      state.notifications.push(notification);
    },
  },
});
export default notificationSlice.reducer;

But, it throws the error as shown below: enter image description here

I am just starting to write this reducer and got stuck here. Thanks for your help.

Also, TSnackBarProps is just SnackBarProps type from material-ui with severity property added.

3
  • u should provide more details , like interfaces and actions and some more . and i think your reducer looks weird! Commented Dec 10, 2020 at 7:15
  • How its related to redux toolkit? You assign readonly string[] instead of string[] Commented Dec 10, 2020 at 7:16
  • @b3hr4d Full code added. Commented Dec 10, 2020 at 7:35

1 Answer 1

1

immer's Draft type, which is used by RTK removes the readonly temporarily from all state types so that you can freely modify it. Unfortunately, that goes a little bit too far in this case.

But of course: you know better than TypeScript here. So you could just cast your state variable, which is Draft<INotificationState> at the moment to INotificationState to assign to it, which is a perfectly valid thing to do in a situation like this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.