-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathbalanceStore.ts
36 lines (33 loc) · 973 Bytes
/
balanceStore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { create } from 'zustand';
import { zustandStorage } from '@/store/mmkv-storage';
import { createJSONStorage, persist } from 'zustand/middleware';
export interface Transaction {
id: string;
title: string;
amount: number;
date: Date;
}
export interface BalanceState {
transactions: Array<Transaction>;
runTransaction: (transaction: Transaction) => void;
balance: () => number;
clearTransactions: () => void;
}
export const useBalanceStore = create<BalanceState>()(
persist(
(set, get) => ({
transactions: [],
runTransaction: (transaction: Transaction) => {
set((state) => ({ transactions: [...state.transactions, transaction] }));
},
balance: () => get().transactions.reduce((acc, transaction) => acc + transaction.amount, 0),
clearTransactions: () => {
set({ transactions: [] });
},
}),
{
name: 'balance',
storage: createJSONStorage(() => zustandStorage),
}
)
);