From d8c5b22d5550680847d43c86c879c138214fc21b Mon Sep 17 00:00:00 2001 From: Iarlen Date: Sun, 11 Feb 2024 20:34:37 -0300 Subject: [PATCH] refactor: refactoring TargetContext and using localstorage to store the data. --- frontend/src/context/TargetContext.tsx | 49 +++++++++++++------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/frontend/src/context/TargetContext.tsx b/frontend/src/context/TargetContext.tsx index de595db9..06028c1d 100644 --- a/frontend/src/context/TargetContext.tsx +++ b/frontend/src/context/TargetContext.tsx @@ -13,6 +13,7 @@ type TargetContextValue = { targets: TargetProps[] | undefined; addTarget: (target: Omit) => void; getTargetById: (id: number) => TargetProps | undefined; + incrementEntry: (id: number, entry: Entry) => void; }; const TargetContext = createContext(null); @@ -28,36 +29,18 @@ export interface TargetProps { name: string; target: number; currentValue: number; - unit: string; + unity: string; entries?: Entry[]; } -const defaultTargets: TargetProps[] = [ - { - id: Date.now(), - name: "Correr 100 km", - target: 100, - currentValue: 50, - unit: "Km (Quilò‚metro)", - entries: [ - { - value: 5, - date: "2022-01-01", - notes: "Corrir na praia da barra", - }, - { - value: 2, - date: "2022-01-02", - notes: "Corrir na esteira da academia", - }, - ], - }, -]; - export const TargetContextProvider: React.FC = ({ children, }) => { - const [targets, setTargets] = useState(defaultTargets); + const [targets, setTargets] = useState( + localStorage.getItem("targets") + ? JSON.parse(localStorage.getItem("targets")!) + : [] + ); const userId = "ZR9MbNxPj6CfaoHgnXoq"; @@ -73,13 +56,29 @@ export const TargetContextProvider: React.FC = ({ [targets] ); + const incrementEntry = useCallback((id: number, entry: Entry) => { + setTargets((prev) => + prev?.map((target) => { + if (target.id === id) { + return { + ...target, + currentValue: target.currentValue + entry.value, + entries: [...(target.entries || []), entry], + }; + } + return target; + }) + ); + }, []); + const contextValue = useMemo( () => ({ targets, addTarget, getTargetById, + incrementEntry, }), - [addTarget, targets, getTargetById] + [addTarget, targets, getTargetById, incrementEntry] ); useEffect(() => {