Use createSlice in actions/alerts

For #26556

Instead of splitting out reducers and actions, we can combine them via
RTK's `createSlice`.

I considered moving this into a `slices` directory, so if you'd rather
that let me know.
This commit is contained in:
Brad Dunbar 2025-10-01 10:17:12 -04:00
parent 3ee1378932
commit bd43a118ec
No known key found for this signature in database
GPG Key ID: C32E3CC9B201C719
3 changed files with 31 additions and 30 deletions

View File

@ -1,6 +1,7 @@
import { defineMessages } from 'react-intl';
import { createAction } from '@reduxjs/toolkit';
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import { AxiosError } from 'axios';
import type { AxiosResponse } from 'axios';
@ -27,13 +28,36 @@ const messages = defineMessages({
},
});
export const dismissAlert = createAction<{ key: number }>('alerts/dismiss');
const initialState: Alert[] = [];
let id = 0;
export const clearAlerts = createAction('alerts/clear');
export const { actions, reducer } = createSlice({
name: 'alerts',
initialState,
reducers: {
clearAlerts() {
return [];
},
export const showAlert = createAction<Omit<Alert, 'key'>>('alerts/show');
dismissAlert(state, action: PayloadAction<{ key: number }>) {
const { key } = action.payload;
return state.filter((item) => item.key !== key);
},
const ignoreAlert = createAction('alerts/ignore');
ignoreAlert(state) {
return state;
},
showAlert(state, action: PayloadAction<Omit<Alert, 'key'>>) {
state.push({
key: id++,
...action.payload,
});
},
},
});
export const { clearAlerts, dismissAlert, ignoreAlert, showAlert } = actions;
export const showAlertForError = (error: unknown, skipNotFound = false) => {
if (error instanceof AxiosError && error.response) {

View File

@ -1,24 +0,0 @@
import { createReducer } from '@reduxjs/toolkit';
import { showAlert, dismissAlert, clearAlerts } from 'mastodon/actions/alerts';
import type { Alert } from 'mastodon/models/alert';
const initialState: Alert[] = [];
let id = 0;
export const alertsReducer = createReducer(initialState, (builder) => {
builder
.addCase(showAlert, (state, { payload }) => {
state.push({
key: id++,
...payload,
});
})
.addCase(dismissAlert, (state, { payload: { key } }) => {
return state.filter((item) => item.key !== key);
})
.addCase(clearAlerts, () => {
return [];
});
});

View File

@ -3,10 +3,11 @@ import { Record as ImmutableRecord, mergeDeep } from 'immutable';
import { loadingBarReducer } from 'react-redux-loading-bar';
import { combineReducers } from 'redux-immutable';
import { reducer as alertsReducer } from '../actions/alerts';
import { accountsReducer } from './accounts';
import { accountsFamiliarFollowersReducer } from './accounts_familiar_followers';
import { accountsMapReducer } from './accounts_map';
import { alertsReducer } from './alerts';
import announcements from './announcements';
import { composeReducer } from './compose';
import { contextsReducer } from './contexts';