Graphql - Expected Name, found "(" - reactjs

Hi I have a mutatuion that works in Playground but when trying to but it into a React app I get the error
Expected Name, found "(".
Its a text app where messages can be added.
In the Playground the mutataion works
mutation addTextToChat {
addTextToGroupChat(addMessageInput: {
chatId:"557633398-w33",
message: "New Message"
}) {
successful
}
}
and the message is added.
I'm trying to put this mutation into a React app like
export const AddTextToChatMutation = gql`
mutation AddTextToChat($addMessage: AddMessage!) {
addTextToGroupChat:(
addTextInput(message: $addMessage){
conversationId
message
}
)
{
successful
}
}
`
but I get the error Expected Name, found "(".
Updated mutation
export const AddTextToChatMutation = gql`
mutation AddTextToChat($addMessage: AddMessage!) {
addTextToGroupChat:{
addTextInput(message: $addMessage){
conversationId
message
}
{
successful
}
}
`

Related

Showing bad request while fetching data using graphQl?

The getProductById is in another js file. When I am trying to use this by putting some static id in gql playground, it is working,
export const getProductById = gql`
query getProductById($id: String!) {
product(id: $id) {
id
brand
name
gallery
inStock
prices {
currency
amount
}
category
description
attributes {
id
name
type
items {
displayValue
value
id
}
}
}
}
`;
const{data, loading, error} = useQuery(getProductById,{
variables:{id}
})
When I am consoling log data it is showing undefined.
It is also returning error which is
Error: Response not successful: Received status code 400

Error: Response not successful: Received status code 400

The application uses apollo server and react in the frontend. In the backend I use apollo server. The request works via the Playground and Postman and I don't get any errors. Queries in the frontend without parameters also work perfectly. When I make a mutation in the frontend, I get the following error error: Response not successful: Received status code 400. When print debugging in the backend, I also don't get any args. In the Web-console: The XHR POST http://localhost:4000/ contains the following request: {"variables":{},"query":"mutation ($title: String!, $dotColor: String!) {\n newStack(title: $title, dotColor: $dotColor) {\n stackID\n title\n dotColor\n __typename\n }\n}\n"}
src/queries/queries.js
import { gql } from "#apollo/client";
[...]
const newStackMutation = gql`
mutation($title: String!, $dotColor: String!) {
newStack(title: $title, dotColor: $dotColor) {
stackID
title
dotColor
}
}
`;
[...]
export {[...], newStackMutation};
src/components/NewStack.js
import { useMutation } from "#apollo/client";
import { newStackMutation } from "../queries/queries";
import { useState } from "react";
export default function NewStack() {
const [newStack] = useMutation(newStackMutation);
const handleNewStackSubmit = (e) => {
//newStack({variables}); actually I would pass the variables from the setState here
newStack({ title: "Test", dotColor: "red" });
};
return (
<div>
<form onSubmit={handleNewStackSubmit}>
[...]
<button type="submit" />
</div>
</form>
</div>
);
};
Ah, you know what its probably because you need to add the name of the mutation
const newStackMutation = gql`
mutation newStack($title: String!, $dotColor: String!) {
newStack(title: $title, dotColor: $dotColor) {
stackID
title
dotColor
}
}
`;// Notice the `newStack` next to `mutation`, that should work
Also this
newStack({variables: { title: "Test", dotColor: "red" }});

Can't pass arguments in useQuery with React-Query + Graphql-Request

I'm a bit stuck. I am using graphql-request with react-query, following the example code quite closely. I replaced it with my own backend, and it works when I don't use variables, but hardcode the values. It also all works in my GraphiQL test environment.
So doing this works:
export default function usePost(postId) {
return useQuery(
["post", postId],
async () => {
const { post } = await request(
endpoint,
gql`
query {
post(id: "123123123123") { // <--- with the id hard-coded, it works
id
heading
content
}
}
`
)
return post
},
{
enabled: !!postId,
}
)
}
What follows is exactly the same code, but now the previously hard-coded post-id ("123123123123") is replaced by a variable (${postId}). Exactly as described in the example code
export default function usePost(postId) {
return useQuery(
["post", postId],
async () => {
const { post } = await request(
endpoint,
gql`
query {
post(id: ${postId}) { // <--- with the ${postId} variable, things break, but it's exactly the same syntax as in the react-query example & it works in my graphiql backend. Also console-logged the postId, and it is correct
id
heading
content
}
}
`
)
return post
},
{
enabled: !!postId,
}
)
}
The error response is:
commons.js:46154 Error: Syntax Error: Expected :, found ):
{"response":{"errors":[{"message":"Syntax Error: Expected :, found
)","locations":[{"line":3,"column":46}]}],"status":400},"request":{"query":"\n
query {\n post(id: 5fda109506038d9d18fa27e2) {\n
id\n heading\n content\n }\n
}\n "}}
at GraphQLClient. (commons.js:13039)
at step (commons.js:12930)
at Object.next (commons.js:12911)
at fulfilled (commons.js:12902)
I guess it's some syntax that I am getting wrong? Or could it have to do with the fact that now the quotation marks are missing? Though the example code also doesn't do anything differently... Really not sure anymore, but it's literally that one line that breaks it all and that I cannot figure out.
Your id 5fda109506038d9d18fa27e2 looks to be a string but you're not passing it as a string to your back end, which is why you're getting a syntax error.
It looks like this
query {
post(id: 5fda109506038d9d18fa27e2) {
id
title
body
}
}
Notice how there aren't any quotation marks around the id? e.g. "5fda109506038d9d18fa27e2". You can also use integers as ids, I just want to make a point that you're not actually passing an integer. Read more on scalar types here.
I recommend you pass variables how they're intended by graphql rather than using string interpolation. This will help avoid this problem. Read more on variables in graphql here.
Here's an example of passing variables in graphql:
query Post($id: ID!) {
post(id: $id) {
id
title
body
}
}
Here's how it would look using your code:
function usePost(postId) {
return useQuery(
["post", postId],
async () => {
const { post } = await request(
endpoint,
gql`
query Post($id: ID!) {
post(id: $id) {
id
title
body
}
}
`,
{ id: postId }
);
return post;
},
{
enabled: !!postId
}
);
}

what is 'mutation_root' in Apollo-graphql mutations? I'm getting the error that says a field not found in "mutation_root"

I'm following their official tutorial and the query tutorial works perfectly but the mutation throws the error in the title when I press the button in the following code. https://www.apollographql.com/docs/react/data/mutations/
const ADD_USER = gql`
mutation AddUser($name: String!) {
addUser(name: $name) {
name
}
}
`;
const [addUser, {data}] = useMutation(ADD_USER);
<Button
title="press"
onPress={() => addUser({variables: {name: 'Avneesh'}})}
/>

Apollo Client is not reading variables passed in using useQuery hook

Having a weird issue passing variables into the useQuery hook.
The query:
const GET_USER_BY_ID= gql`
query($id: ID!) {
getUser(id: $id) {
id
fullName
role
}
}
`;
Calling the query:
const DisplayUser: React.FC<{ id: string }> = ({ id }) => {
const { data, error } = useQuery(GET_USER_BY_ID, {
variables: { id },
});
return <div>{JSON.stringify({ data, error })}</div>;
};
Rendering the component:
<DisplayUser id="5e404fa72b819d1410a3164c" />
This yields the error:
"Argument \"id\" of required type \"ID!\" was provided the variable \"$id\" which was not provided a runtime value."
Calling the query from GraphQL Playground returns the expected result:
{
"data": {
"getUser": {
"id": "5e404fa72b819d1410a3164c",
"fullName": "Test 1",
"role": "USER"
}
}
}
And calling the query without a variable but instead hard-coding the id:
const GET_USER_BY_ID = gql`
query {
getUser(id: "5e404fa72b819d1410a3164c") {
id
fullName
role
}
}
`;
const DisplayUser: React.FC = () => {
const { data, error } = useQuery(GET_USER_BY_ID);
return <div>{JSON.stringify({ data, error })}</div>;
};
Also returns the expected result.
I have also attempted to test a similar query that takes firstName: String! as a parameter which also yields an error saying that the variable was not provided a runtime value. This query also works as expected when hard-coding a value in the query string.
This project was started today and uses "apollo-boost": "^0.4.7", "graphql": "^14.6.0", and "react-apollo": "^3.1.3".
[Solved]
In reading through the stack trace I noticed the issue was referencing graphql-query-complexity which I was using for validationRules. I removed the validation rules and now everything works! Granted I don't have validation at the moment but at least I can work from here. Thanks to everyone who took the time to respond!
I had also ran into a similar issue and was not really sure what was happening.
There seems to be similar problem reported here - https://github.com/apollographql/graphql-tools/issues/824
We have 2 options to fix the issue.
- First one is a simple fix, where in you don't make the ID mandatory when it takes only a single parameter ( which is not an object )
const GET_USER_BY_ID= gql`
query($id: ID) {
Second option is to use an object as a parameter instead of a primitive. I went ahead with this and it seemed to work fine for me even though I made the object and the property inside to be required.
// On the client
const GET_USER_BY_ID= gql`
query($input: GetUserInput!) {
getUser(input: $input) {
id
fullName
role
}
}`;
const { data, error } = useQuery(GET_USER_BY_ID, {
variables: { input: { id }},
});
// In the server, define the input type
input GetUserInput {
id: ID!
}
Try
const { data, error } = useQuery(GET_USER_BY_ID, { id });

Resources