next.js 支持数据库身份验证侦听器,导致无限重新呈现

6ju8rftf  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(102)

我的应用程序 Package 在一个提供程序中,该提供程序应将会话状态传递给应用程序的其余部分。但是supabase auth listener代码似乎无限地重新呈现我的组件,我不知道如何修复它。提供商代码:

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 };

字符串
我的应用代码

<>
      <AppStateProvider>
          <Component {...pageProps} />
      </AppStateProvider>
    </>
  );
}

zengzsys

zengzsys1#

尝试为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();
    };

  }, []);

字符串

相关问题