代码之家  ›  专栏  ›  技术社区  ›  Stackaccount1

超级身份验证侦听器导致无限重渲染

  •  0
  • Stackaccount1  · 技术社区  · 3 年前

    我的应用程序封装在一个提供程序中,该提供程序应将会话状态传递给应用程序的其余部分。但是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>
        </>
      );
    }
    
    0 回复  |  直到 3 年前
        1
  •  0
  •   thorwebdev    3 年前

    尝试添加的支票 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();
        };
    
      }, []);