Skip to content

Commit

Permalink
fix: update session after each change
Browse files Browse the repository at this point in the history
  • Loading branch information
Pinx0 committed Nov 8, 2024
1 parent b13fc8e commit 4c738b4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 12 deletions.
10 changes: 1 addition & 9 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import './globals.css';
import 'leaflet/dist/leaflet.css';
import SidebarLayout from '@/components/layout/SidebarLayout';
import { ModalProvider } from '@/context/ModalProvider';
import { createClient } from '@/lib/supabase/server';
import { SessionProvider } from '@/context/SessionProvider';
import { Toaster } from 'sonner';
import { PropsWithChildren } from 'react';
Expand All @@ -13,19 +12,12 @@ export const metadata = {
description: 'Sistema de coordinación para emergencias en la Comunidad Valenciana',
};

const getSession = async () => {
const supabase = await createClient();
const { data, error } = await supabase.auth.getUser();
return data;
};

export default async function RootLayout({ children }: PropsWithChildren) {
const session = await getSession();
return (
<html lang="es">
<body suppressHydrationWarning={true}>
<Toaster position="bottom-left" richColors />
<SessionProvider session={session}>
<SessionProvider>
<QueryClientProvider>
<ModalProvider>
<SidebarLayout>{children}</SidebarLayout>
Expand Down
26 changes: 23 additions & 3 deletions src/context/SessionProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,37 @@
'use client';
import React, { createContext, ReactNode, useContext } from 'react';
import React, { createContext, ReactNode, useContext, useEffect, useState } from 'react';
import { User } from '@supabase/auth-js';
import { supabase } from '@/lib/supabase/client';

const SessionContext = createContext<UserSession>({ user: null });

type UserSession = { user: User } | { user: null };

type SessionProviderProps = {
children: ReactNode;
session: UserSession;
};

export const SessionProvider: React.FC<SessionProviderProps> = ({ children, session }) => {
export const SessionProvider: React.FC<SessionProviderProps> = ({ children }) => {
const [session, setSession] = useState<UserSession>(() => ({ user: null }));

useEffect(() => {
// Fetch initial session
const fetchSession = async () => {
const { data } = await supabase.auth.getUser();
setSession(data);
};
fetchSession();

// Subscribe to session changes
const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
setSession(() => ({ user: session?.user ?? null })); // Update the session in state
});

// Clean up listener on component unmount
return () => {
authListener?.subscription.unsubscribe();
};
}, []);
return <SessionContext.Provider value={session}>{children}</SessionContext.Provider>;
};

Expand Down

0 comments on commit 4c738b4

Please sign in to comment.