无法从next.js应用程序向graphQL数据库发送数据

7vux5j2d  于 2023-03-08  发布在  其他
关注(0)|答案(1)|浏览(90)

我正在做一个Reddit克隆。我已经到了SQL实现的阶段,所以我使用graphQL,并使端点更容易Stepzen。下面的代码是我的Reddit站点邮箱沿着graphQL、Mutations.ts和Queries. ts。
我已经添加了阿波罗客户端和烤面包机以及。
问题似乎发生在我的PostBox.tsx中,它来自我的onSubmit函数。当Try/Catch运行时,它触发错误并捕获它。
在控制台中,我的formData是成功的,try内部的控制台日志立即工作,但没有其他功能。
PostBox.tsx

import { useSession } from 'next-auth/react';
import React, { useState } from 'react';
import Avatar from './Avatar';
import { LinkIcon, PhotographIcon } from '@heroicons/react/outline';
import { useForm } from 'react-hook-form';
import { useMutation } from '@apollo/client';
import { ADD_POST, ADD_SUBREDDIT } from '../graphql/mutations';
import client from '../apollo-client';
import { GET_SUBREDDIT_BY_TOPIC } from '../graphql/queries';
import toast from 'react-hot-toast';
type FormData = {
    postTitle: string;
    postBody: string;
    postImage: string;
    subreddit: string;
};

function PostBox() {
    const { data: session } = useSession();
    // console.log(session);
    //
    const [addPost] = useMutation(ADD_POST);
    const [addSubreddit] = useMutation(ADD_SUBREDDIT);
    //
    const [imageBoxOpen, setImageBoxOpen] = useState<boolean>(false);
    const {
        register,
        setValue,
        handleSubmit,
        watch,
        formState: { errors },
    } = useForm<FormData>();

    const onSubmit = handleSubmit(async (formData) => {
        console.log(formData);
        console.log('form data');
        const notification = toast.loading('Creating new post...');
        console.log(notification, 'notification');
        try {
            // query for subreddit topic
            console.log('Test 1 Success');
            //
            // Error below: CL Test in line 42 is a success
            const {
                data: { getSubredditListByTopic },
            } = await client.query({
                query: GET_SUBREDDIT_BY_TOPIC,
                variables: {
                    topic: formData.subreddit,
                },
            });

            const subredditExists = getSubredditListByTopic.length > 0;
            console.log('Test 2 Failed');
            if (!subredditExists) {
                // create subreddit
                console.log('subreddit is new creating a new subreddit!');
                console.log('Test 3 Failed');
                const {
                    data: { insertSubreddit: newSubreddit },
                } = await addSubreddit({
                    variables: {
                        topic: formData.subreddit,
                    },
                });
                console.log('Creating post...', formData);
                const image = formData.postImage || '';

                const {
                    data: { insertPost: newPost },
                } = await addPost({
                    variables: {
                        body: formData.postBody,
                        image: image,
                        subreddit_id: newSubreddit.id,
                        title: formData.postTitle,
                        username: session?.user?.name,
                    },
                });
                console.log('New post added:', newPost);
            } else {
                // use existing

                const image = formData.postImage || '';
                const {
                    data: { insertPost: newPost },
                } = await addPost({
                    variables: {
                        body: formData.postBody,
                        image: image,
                        subreddit_id: getSubredditListByTopic[0].id,
                        title: formData.postTitle,
                        username: session?.user?.name,
                    },
                });
                console.log('New post added', newPost);
            }

            setValue('postBody', '');
            setValue('postImage', '');
            setValue('postTitle', '');
            setValue('subreddit', '');
            toast.success('New Post Created!', {
                id: notification,
            });
        } catch (error) {
            toast.error('Whoops something went wrong!', {
                id: notification,
            });
        }
    });

queries.ts

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

export const GET_SUBREDDIT_BY_TOPIC = gql`
    query MyQuery($topic: String!) {
        getSubredditListByTopic(topic: $topic) {
            id
            topic
            created_at
        }
    }
`;

Mutations.ts

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

export const ADD_POST = gql`
    mutation MyMutation(
        $body: String!
        $image: String!
        $subreddit_id: ID!
        $title: String!
        $username: String!
    ) {
        insertPost(
            body: $body
            image: $image
            subreddit_id: $subreddit_id
            title: $title
            username: $username
        ) {
            body
            created_at
            id
            image
            subreddit_id
            title
            username
        }
    }
`;

export const ADD_SUBREDDIT = gql`
    mutation MyMutation($topic: String!) {
        insertSubreddit(topic: $topic) {
            id
            topic
            created_at
        }
    }
`;

graphql -〉这个文件还有更多的内容,但我只修改了这两个,其余的都是Supabase自动生成的

getSubredditList: [Subreddit]
    @dbquery(
        type: "postgresql"
        schema: "public"
        table: "subreddit"
        configuration: "postgresql_config"
       )
        

getSubredditListByTopic(topic: String!): [Subreddit]
    @dbquery(
        type: "postgresql"
        schema: "public"
        query: """
        select * from "subreddit" where "topic" = $1
        """
        configuration: "postgresql_config"
        )

这真的让我很不安,因为我不知道出了什么问题。谢谢大家看一看!

czq61nw1

czq61nw11#

我遇到过类似的问题,使用useLazyQuery解决了它,它按需执行查询。
1.导入useLazyQuery
1.从useLazyQuery获取listSubreddits(或您将称之为它的任何名称)引用
1.修改try

import { useMutation, useLazyQuery } from "@apollo/client";
// other imports

export default function PostBox({ subreddit }: Props) {

//...
    const [listSubreddits] = useLazyQuery(GET_SUBREDDIT_BY_TOPIC);
//...

    const onSubmit = handleSubmit(async (formData) => {
        console.log(formData);
        const notification = toast.loading("Creating new post...");

        try {
            // Query for the subreddit topic...
            const {
                data: { getSubredditListByTopic },
            } = await listSubreddits({
                query: GET_SUBREDDIT_BY_TOPIC,
                variables: {
                    topic: subreddit || formData.subreddit,
                },
        });

        const subredditExists = getSubredditListByTopic.length > 0;

// And so on...

相关问题