reactjs - Kan inte skicka data till GraphQL-databas från next.js-app


Jag håller på att göra en Reddit-klon. Jag har kommit till punkten för implementering av SQL, så jag använder graphQL och för att göra detta enklare Stepzen för endpoints. Följande kod är min Post Box för reddit-sidan tillsammans med graphQL, Mutations.ts och Queries.ts.

Jag har också lagt till Apollo Client och Toaster.

Problemet verkar uppstå i min PostBox.tsx. Det kommer från min onSubmit-funktion. När Try/Catch körs utlöser det felet och fångar det.

I konsolen är min formData ett framgångsresultat och console Loggen direkt inne i try fungerar, men inget annat.

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

index.graphql -> Det finns mer i denna fil men det här är de enda två jag har ändrat, Supabase byggde automatiskt resten

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"
        )

Det här upprör mig verkligen eftersom jag inte är säker på vad som är fel. Tack allihopa för att ni tittar på det!

Svar #1

Jag hade ett liknande problem och löste det genom att använda useLazyQuery, som kör frågor på begäran.

  1. Importera useLazyQuery
  2. Hämta listSubreddits (eller vad du nu kommer att kalla det) referens från useLazyQuery
  3. Modifiera try-blocket

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...