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 { queryConversationCount } from '@proton/shared/lib/api/conversations';
8 import { type LabelCount } from '@proton/shared/lib/interfaces';
10 const name = 'conversationCounts' as const;
13 [name]: ModelState<LabelCount[]>;
16 type SliceState = State[typeof name];
17 type Model = NonNullable<SliceState['value']>;
19 export const selectConversationCounts = (state: State) => state[name];
21 const modelThunk = createAsyncModelThunk<Model, State, ProtonThunkArguments>(`${name}/fetch`, {
22 miss: async ({ extraArgument }) => {
23 return extraArgument.api(queryConversationCount()).then(({ Counts }) => Counts);
25 previous: previousSelector(selectConversationCounts),
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.ConversationCounts) {
41 state.value = action.payload.ConversationCounts;
47 export const conversationCountsReducer = { [name]: slice.reducer };
48 export const conversationCountsActions = slice.actions;
49 export const conversationCountsThunk = modelThunk.thunk;
51 const hooks = createHooks(conversationCountsThunk, selectConversationCounts);
53 export const useConversationCounts = hooks.useValue;
54 export const useGetConversationCounts = hooks.useGet;