Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't send data to graphQL database from next.js app

I am making a Reddit Clone. I have gotten to the point of implementation of SQL, so I am using graphQL and to make this easier Stepzen for endpoints. The following code is my Post Box for the reddit site along with graphQL, Mutations.ts and Queries.ts.

I have added Apollo Client and Toaster as well.

The problem seems to be occurring in my PostBox.tsx, It is coming from within my onSubmit function. As the Try/Catch runs, it triggers the error and catches it.

In the console my formData is a success and the console Log immediately inside the try works, but nothing else.

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 ->There is more to this file but these are the only two I have changed, Supabase automatically built the rest

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

This is really upsetting me as I am not sure what is wrong. Thank you all for taking a look!

like image 551
AmeriNam20 Avatar asked Nov 27 '25 04:11

AmeriNam20


1 Answers

I had a similar problem, and solved it using useLazyQuery, which executes queries on-demand.

  1. Import useLazyQuery
  2. Get listSubreddits (or whatever you'll call it) reference from useLazyQuery
  3. Modify try block

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...
like image 137
dabcd Avatar answered Nov 29 '25 20:11

dabcd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!