From 386bcae5166155ad831ab0f4818597dd8feec695 Mon Sep 17 00:00:00 2001 From: Roberto Milla Martinez Date: Sun, 17 Nov 2024 02:55:39 +0100 Subject: [PATCH] feat: use town provider correctly --- src/app/layout.tsx | 9 ++++++--- src/context/TownProvider.tsx | 33 ++++++++++++++++++++++++++++++--- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 49d7513a..adbd967e 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -7,6 +7,7 @@ import { Toaster } from 'sonner'; import { PropsWithChildren } from 'react'; import { QueryClientProvider } from '@/context/QueryClientProvider'; import { RoleProvider } from '@/context/RoleProvider'; +import { TownProvider } from '../context/TownProvider'; export const metadata = { title: 'Ajuda Dana - Sistema de CoordinaciĆ³n', @@ -21,9 +22,11 @@ export default async function RootLayout({ children }: PropsWithChildren) { - - {children} - + + + {children} + + diff --git a/src/context/TownProvider.tsx b/src/context/TownProvider.tsx index 495c7300..897b1f50 100644 --- a/src/context/TownProvider.tsx +++ b/src/context/TownProvider.tsx @@ -3,8 +3,29 @@ import { useQuery } from '@tanstack/react-query'; import { Town } from '@/types/Town'; import { getTowns } from '@/lib/actions'; +import { createContext, ReactNode, useContext, useEffect, useState } from 'react'; -export const useTowns = () => { +export type TownContextData = { + towns: Town[]; + isLoading: boolean; + error: Error | null; + getTownById: (id: number) => Town | null; +}; + +const TownContext = createContext({ + towns: [], + isLoading: false, + error: null, + getTownById: () => { + return null; + }, +}); + +type TownProviderProps = { + children: ReactNode; +}; + +export const TownProvider: React.FC = ({ children }) => { const { data: towns, isLoading, @@ -14,7 +35,13 @@ export const useTowns = () => { queryFn: () => getTowns(), }); - const getTownById = (id: number) => towns?.find((t) => t.id === id); + const getTownById = (id: number): Town | null => towns?.find((t) => t.id === id) || null; - return { towns: towns ?? [], isLoading, error, getTownById }; + return ( + + {children} + + ); }; + +export const useTowns = () => useContext(TownContext);