【问题标题】:next-auth using graphql apollo as data sourcenext-auth 使用 graphql apollo 作为数据源
【发布时间】:2022-11-11 01:32:52
【问题描述】:

嗨 stackoverflow 社区,

我需要一些帮助,

我有一个 GraphQL 数据源,我正在使用 apollo 客户端来提取这些数据。 我目前正在开发我的登录功能;我正在使用下一个身份验证凭据提供程序,这是我的凭据提供程序 api 端点

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import getUser from "src/query/getUser";

export default NextAuth({
    session: {
        strategy: 'jwt',
    },
    callbacks: {
        async jwt({ token, user}: any) {
            if(user?._id) token._id = user._id;
            return token;
        },
        async session({ session, token}: any) {
            if(token?._id) session.user._id = token._id;
            return session;
        },
    },
    providers: [
        CredentialsProvider({
            async authorize(credentials: any) {
                
                const email = credentials.email;
                // here is where i get the error - Cannot read properties of null (reading 'useContext')
                const { data } = await getUser(email);
                    
                if(data.password === credentials.password) {
                    return {
                        _id: data.id,
                        name: data.username,
                        email: data.email,
                    };
                } 
                throw new Error("Invalid email or password");
            },
        }),
    ],
}); 

这是我的 getUser 钩子

import { useQuery, gql } from '@apollo/client';

const Get_User = gql`
query User($email: String!) {
  user(email: $email) {
    id
    username
    email
    password
  }
}
`;


export default function getUser(email: any) {
    const { error,  data } = useQuery(Get_User, {variables: {email}});

    return {
        error,
        data,
    }
}

我已经通过注释掉 GraphQL getUser 并更改与自身比较的 if 语句 (credential.password === credential.password) 并返回静态写入的数据来验证我的下一个身份验证端点正在工作。

我还验证了我的 getUser 钩子通过在我的登录页面上调用它并让它记录返回到控制台来返回正确的数据。

还检查凭据对象内的数据是否正确传递和访问值。

我想我在这里违反了一些反应钩子法,但我不太清楚如何解决这个问题,任何启示将不胜感激。提前致谢! ^-^

【问题讨论】:

    标签: typescript next.js graphql apollo-client next-auth


    【解决方案1】:

    您在不是 React 组件的函数中使用了钩子,即您的 GetUser 函数返回一个对象而不是其他组件。加上useQuery 是异步的,因此函数实际上不会返回数据。

    您可以在 client 是您的 Apollo 客户端对象的函数中使用 client.query。或者您可以在实际的反应组件中使用useQuery

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 2020-02-12
      • 2020-07-15
      • 2019-08-22
      • 2018-08-24
      • 2019-02-02
      • 2017-08-01
      • 2020-10-16
      相关资源
      最近更新 更多