Reputation: 149
My app is wrapped in a provider that should pass the session state to the rest of the app. But the supabase auth listener code seems to infinitely rerender my component and I cannot figure out how to fix it. The provider code:
import React, { createContext, useState, useEffect } from "react";
import { createClient } from "@supabase/supabase-js";
import { supabasekey } from "../../constants";
const supabaseUrl = "https://**************.supabase.co";
const supabase = createClient(supabaseUrl, supabasekey["1"]);
const MyContext = createContext();
const AppStateProvider = ({ children }) => {
const [state, setState] = useState(/* initial state */);
//Supabase auth functions causing infinite re-rendering of components
useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => {
setState(session?.user ?? null);
});
supabase.auth.onAuthStateChange((_event, session) => {
setState(session?.user ?? null);
});
}, []);
console.log("provider running");
// Create the context value
const contextValue = {
state,
setState,
};
return (
<MyContext.Provider value={contextValue}>{children}</MyContext.Provider>
);
};
export { MyContext, AppStateProvider };
my app code
<>
<AppStateProvider>
<Component {...pageProps} />
</AppStateProvider>
</>
);
}
Upvotes: 0
Views: 253
Reputation: 1
It's resolved in https://github.com/supabase/gotrue-js/issues/762. It's because you are trying to use getSession in asyn.
Upvotes: 0
Reputation: 1162
Try adding a check for if (event === 'SIGNED_IN')
:
useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => {
setState(session?.user ?? null);
});
const {
data: { subscription }
} = supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_IN') setState(session?.user ?? null);
});
return () => {
subscription.unsubscribe();
};
}, []);
Upvotes: 0