简体   繁体   English

导航栏中的用户名 Next.js -Typescript-Supabase

[英]Username in Navbar Next.js -Typescript-Supabase

I am trying to get the username of a user in my navbar.我正在尝试在我的导航栏中获取用户的用户名。 The username = the column "username" of the table "profiles" in my Supabase db.用户名 = 我的 Supabase 数据库中表"profiles"的“用户名”列。 As you can see bellow, it is filled with the users emails at the moment.正如您在下面看到的,它现在充满了用户的电子邮件。 I can't change it simply to user.username because "user" is the wrong table..我不能简单地将它更改为 user.username 因为“用户”是错误的表..

My navbar.tsx component looks like this:我的 navbar.tsx 组件如下所示:

    import { useUser, useSupabaseClient } from "@supabase/auth-helpers-react";
    import { useRouter } from "next/router";
    import Link from "next/link";

    const NavbarComponent = () => {
    const supabaseClient = useSupabaseClient();
    const user = useUser();
    const router = useRouter();

    function signOutUser() {
        supabaseClient.auth.signOut();
        router.push("/"); // localhost:3000
    }
    return (
        <Navbar isBordered isCompact>
            <Navbar.Brand as={Link} href="/">
                ShareArticles
            </Navbar.Brand>
            <Navbar.Content hideIn="xs" variant="highlight-rounded">
                <Navbar.Link href="/mainFeed">Main Feed</Navbar.Link>
                <Navbar.Link href="/createArticle">Create Article</Navbar.Link>
            </Navbar.Content>

            <Navbar.Content>
                {!user ?  /*User doesnt exist*/
                    <>
                        <Navbar.Link href="/login">
                            <Button auto flat>
                                Login
                            </Button>
                        </Navbar.Link>
                    </>
                :         /* User does exist */
                    <>
                        <Navbar.Item>
                            <Navbar.Link href="/updateAccount">{user?.email}</Navbar.Link> 
                            // Here is now the email, but I want the username! of the table profiles

                        </Navbar.Item>
                        <Navbar.Item>
                            <Button auto flat onPress={() => signOutUser()}>
                                Sign Out
                            </Button>
                        </Navbar.Item>
                    </>
                }  
            </Navbar.Content>
        </Navbar>
    ) 
    }
    export default NavbarComponent;  

my _app.tsx looks like this:我的 _app.tsx 看起来像这样:

     import { createBrowserSupabaseClient } from "@supabase/auth-helpers-nextjs";
     import { SessionContextProvider } from "@supabase/auth-helpers-react";
     import { useState } from "react";
     import { NextUIProvider } from "@nextui-org/react";
     import { Box } from "../components/Box";
     import Navbar from '../components/NavbarComponent';
     import { userAgent } from 'next/server';

      // Providers (providing Supabase to our application, nextui providers)
      // Navbar

     // Navbar
     // Box (container for the content)

    function MyApp({ Component, pageProps }: AppProps) {
       const [supabaseClient] = useState(() => createBrowserSupabaseClient());
    // Supabase URL? Supabase Anon key? CREATE A SUPABASE ACCOUNT

    return  (
    <SessionContextProvider
      supabaseClient={supabaseClient}
    >
      <NextUIProvider>
        <Navbar/>
        <Box css={{ px: "$12", py: "$15", mt: "$12", "@xsMax": {px: "$10"}, maxWidth: "800px", margin: "0 auto" }}>
          <Component {...pageProps} />
        </Box>
      </NextUIProvider>
    </SessionContextProvider>
     )
    }
    export default MyApp

Thanks in advance!提前致谢!

I already tried changing the useUser to useProfiles and adding我已经尝试将useUser更改为useProfiles并添加

type Profiles = Database["public"]["Tables"]["profiles"]["Row"];

But nothing worked.. I am a new to the Nextjs framework and I can't find anything useful about fetching of data from supabase tables execpt the docs of supabase itself.但没有任何效果.. 我是 Nextjs 框架的新手,我找不到任何关于从 supabase 表中获取数据的有用信息,执行 supabase 本身的文档。 Sorry for my bad english..Thanks in advance抱歉我的英语不好..提前致谢

Are you using any starter template or are following any tutorial?您是否正在使用任何入门模板或正在学习任何教程?

useUser is a hook that's implemented by the auth-helper to provide the user object. useUser是一个由auth-helper实现的钩子,用于提供用户 object。

To get that data from your profiles table, you can use supabase-js:要从您的配置文件表中获取该数据,您可以使用 supabase-js:

const getUserDetails = () => supabase.from('profiles').select('username').single();

You can implement your own hook that you can use throughout your application to reference back to the user details.您可以实现自己的挂钩,您可以在整个应用程序中使用它来引用回用户详细信息。

You can find an example of such a hook implementation here: https://github.com/vercel/nextjs-subscription-payments/blob/main/utils/useUser.tsx您可以在此处找到此类挂钩实现的示例: https://github.com/vercel/nextjs-subscription-payments/blob/main/utils/useUser.tsx

I did it, the solution:我做到了,解决方法:

import { Navbar, Button, Text } from "@nextui-org/react";
import {  useSupabaseClient, useUser } from "@supabase/auth-helpers-react";
import { useRouter } from "next/router";
import Link from "next/link";
// import { useUser } from '@utils/useUser';
import { User } from '@supabase/supabase-js';
import { useEffect, useState } from "react";
const NavbarComponent = () => {
    const supabaseClient = useSupabaseClient();
    const user = useUser();
    const router = useRouter();
    const [profile, setProfile] = useState<any>({});

    useEffect( () => {
        async function getProfile() {
            const {data, error} = await supabaseClient
                .from("profiles")
                .select("*")
                .filter("id", "eq", user?.id)
                .single();
            if (error) {
                console.log(error);
            } else {
                setProfile(data);
            }
        }
        if(typeof user?.id !== "undefined") {
            getProfile();
        }
    }, [user?.id])


    function signOutUser() {
        supabaseClient.auth.signOut();
        router.push("/"); // localhost:3000
    }
    return (
        <Navbar isBordered isCompact>
            <Navbar.Brand as={Link} href="/">
                ShareArticles
            </Navbar.Brand>
            <Navbar.Content hideIn="xs" variant="highlight-rounded">
                <Navbar.Link href="/mainFeed">Main Feed</Navbar.Link>
                <Navbar.Link href="/createArticle">Create Article</Navbar.Link>
            </Navbar.Content>

            <Navbar.Content>
                {!user ?  /*User doesnt exist*/
                    <>
                        <Navbar.Link href="/login">
                            <Button auto flat>
                                Login
                            </Button>
                        </Navbar.Link>
                    </>
                :         /* User does exist */
                    <>
                        <Navbar.Item>
                            <Navbar.Link href="/updateAccount">{profile.username}</Navbar.Link>
                        </Navbar.Item>
                        <Navbar.Item>
                            <Navbar.Link href="/testNav">testNav</Navbar.Link>
                        </Navbar.Item>
                        <Navbar.Item>
                            <Button auto flat onPress={() => signOutUser()}>
                                Sign Out
                            </Button>
                        </Navbar.Item>
                    </>
                }  
            </Navbar.Content>
        </Navbar>
    )
}

export default NavbarComponent;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM