Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / mail / counts / conversationCounts.ts
blob487638b4df5f6524de0eac0fad742dd9649a81a2
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;
12 interface State {
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);
24     },
25     previous: previousSelector(selectConversationCounts),
26 });
28 const initialState = getInitialModelState<Model>();
29 const slice = createSlice({
30     name,
31     initialState,
32     reducers: {
33         set: (state, action: PayloadAction<LabelCount[]>) => {
34             state.value = action.payload;
35         },
36     },
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;
42             }
43         });
44     },
45 });
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;