Skip to content

Commit

Permalink
feat: use town provider correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
Roberto Milla Martinez committed Nov 17, 2024
1 parent af60a84 commit 386bcae
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
9 changes: 6 additions & 3 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -21,9 +22,11 @@ export default async function RootLayout({ children }: PropsWithChildren) {
<SessionProvider>
<RoleProvider>
<QueryClientProvider>
<ModalProvider>
<SidebarLayout>{children}</SidebarLayout>
</ModalProvider>
<TownProvider>
<ModalProvider>
<SidebarLayout>{children}</SidebarLayout>
</ModalProvider>
</TownProvider>
</QueryClientProvider>
</RoleProvider>
</SessionProvider>
Expand Down
33 changes: 30 additions & 3 deletions src/context/TownProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<TownContextData>({
towns: [],
isLoading: false,
error: null,
getTownById: () => {
return null;
},
});

type TownProviderProps = {
children: ReactNode;
};

export const TownProvider: React.FC<TownProviderProps> = ({ children }) => {
const {
data: towns,
isLoading,
Expand All @@ -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 (
<TownContext.Provider value={{ towns: towns || [], isLoading, error, getTownById }}>
{children}
</TownContext.Provider>
);
};

export const useTowns = () => useContext(TownContext);

0 comments on commit 386bcae

Please sign in to comment.