-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.tsx
47 lines (40 loc) · 961 Bytes
/
context.tsx
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
37
38
39
40
41
42
43
44
45
46
47
import {
createContext,
useState,
useContext,
Dispatch,
SetStateAction,
useEffect,
} from 'react';
import { FormFields } from './types';
interface TrakerState {
expenses: FormFields[];
budget: number;
setExpenses: Dispatch<SetStateAction<FormFields[]>>;
setBudget: Dispatch<SetStateAction<number>>;
}
const Traker = createContext<TrakerState>({
expenses: [],
budget: 0,
setExpenses: () => {},
setBudget: () => {},
});
export const useTraker = () => {
return useContext(Traker);
};
export default function TrakerProvider({
children,
}: {
children: JSX.Element;
}) {
const [expenses, setExpenses] = useState<FormFields[]>([]);
const [budget, setBudget] = useState(0);
useEffect(() => {
setBudget(expenses.reduce((sum, cur) => sum + parseFloat(cur.amount), 0));
}, [expenses]);
return (
<Traker.Provider value={{ expenses, budget, setExpenses, setBudget }}>
{children}
</Traker.Provider>
);
}