Merge branch 'renovate/all-minor-patch' into 'main'
[ProtonMail-WebClient.git] / packages / mail / counts / messageCounts.ts
blob26e3228b1982f8df1ae5e5f6b6b2969ae5067c20
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;
12 interface State {
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);
24     },
25     previous: previousSelector(selectMessageCounts),
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.MessageCounts) {
41                 state.value = action.payload.MessageCounts;
42             }
43         });
44     },
45 });
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;