1 import { type PayloadAction, createSlice } from '@reduxjs/toolkit';
3 import { type ModelState, getInitialModelState, serverEvent } from '@proton/account';
4 import type { ProtonThunkArguments } from '@proton/redux-shared-store-types';
5 import { createAsyncModelThunk, handleAsyncModel, previousSelector } from '@proton/redux-utilities';
6 import { createHooks } from '@proton/redux-utilities';
7 import { queryMessageCount } from '@proton/shared/lib/api/messages';
8 import { type LabelCount } from '@proton/shared/lib/interfaces';
10 const name = 'messageCounts' as const;
13 [name]: ModelState<LabelCount[]>;
16 type SliceState = State[typeof name];
17 type Model = NonNullable<SliceState['value']>;
19 export const selectMessageCounts = (state: State) => state[name];
21 const modelThunk = createAsyncModelThunk<Model, State, ProtonThunkArguments>(`${name}/fetch`, {
22 miss: async ({ extraArgument }) => {
23 return extraArgument.api(queryMessageCount()).then(({ Counts }) => Counts);
25 previous: previousSelector(selectMessageCounts),
28 const initialState = getInitialModelState<Model>();
29 const slice = createSlice({
33 set: (state, action: PayloadAction<LabelCount[]>) => {
34 state.value = action.payload;
37 extraReducers: (builder) => {
38 handleAsyncModel(builder, modelThunk);
39 builder.addCase(serverEvent, (state, action) => {
40 if (state.value && action.payload.MessageCounts) {
41 state.value = action.payload.MessageCounts;
47 export const messageCountsReducer = { [name]: slice.reducer };
48 export const messageCountsThunk = modelThunk.thunk;
49 export const messageCountsActions = slice.actions;
51 const hooks = createHooks(messageCountsThunk, selectMessageCounts);
53 export const useMessageCounts = hooks.useValue;
54 export const useGetMessageCounts = hooks.useGet;