GraphQL gql syntax error: <selection> expected, got '}' and Unknown Fields

Viewed 83

I'm attempting to set up Apollo GraphQL support in a new React project, but when I try to compile a query using gql I keep receiving the error:

Here's the code the entire code of both Server and Client Directories

Why is it throwing an error that messages is an Unknown field in my IDE terminal even though it is defined in my server.js

My chat.jsx in Chat-app/client/chat.jsx

import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql} from "@apollo/client";
import React from "react"

const client = new ApolloClient({
    uri: 'http://localhost:4000/',
    cache: new InMemoryCache()
});

const GET_MESSAGES = gql`
 query {
        messages{
            id
            content
            user
        }
`;

const Messages = ({ user }) => {
    const {data} = useQuery(GET_MESSAGES);
    if (!data) {
        return null;
    }
}

const Chat = () => {
    return (
        <div>
            <Messages user="Jack"/>
        </div>
    )
}

export default () => (
    <ApolloProvider client={client}>
        <Chat/>
    </ApolloProvider>
)

In Chat.jsx file when I define the query under GET_MESSAGES fucntion like

const GET_MESSAGES = gql`
    query {
       
    }`;

IT'S THROWING AN ERROR <selection> expected, got '}'

AND WHEN I DECLARE THE FIELDS MESSAGES UNDER THE query like this

const GET_MESSAGES = gql`
    query {
        messages {
            id
            content
            user
        }
    }`;

It throws Unknown fields

enter image description here

My server.js in chat-app/server/server.js

const {GraphQLServer} = require('graphql-yoga')

const messages = []

const typeDefs = `
    type Message { 
        id: ID!
        user: String!
        content : String!
   }
   
    type Query {
        messages : [Message!]  
    } 
    
    type Mutation {
    postMessage(user: String!, content: String!): ID!
    }
`;

const resolvers = {
    Query:{
        messages: () => messages,
    },
    Mutation:{
        postMessage: (parent, {user, content}) => { 
            const id = messages.length; 
            messages.push({
                id,
                user,
                content
            });
            return id
        }
    }
}

const server = new GraphQLServer({ typeDefs, resolvers });
 server.start(({port}) => {
     console.log(`Server on http://localhost:${port}/`);
 });

I thought this error is occurring because of any closed curly brackets or when some fields are not properly defined while calling the query. But all the fields were perfectly defined. When I created this GET_MESSAGES function that's when the error occurred.

NOTE: MY GRAPHQL PLAYGROUND SERVER IS WORKING PERFECTLY.

Does anyone know what I'm doing wrong here?

I'm following this example here https://github.com/jherr/chat-o-matic

0 Answers
Related