Error: Response not successful: Received status code 400 - reactjs

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

Related

Graphql - Expected Name, found "("

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

update function in the useMutation hook displays the mutation result as undefined

I'm new to GraphQL and had a question about useMutation hook. I want to be able to update the UI by updating the object that has been modified instead of refreshing the UI. The problem is that when i pass the result of useMutation hook to the update function, it displays the result as undefined, but the query goes through and returns the response
I'm executing the useMutation hook on click of a button
<button
onClick={() => {
addTodo('Placeholder') : undefined;
}}
></button>
Button click calls a function called addTodo which executes useMutation hook
const ADD_TODO = gql`
mutation AddTodo($text: String!) {
addTodo(text: $text) {
id
text
}
}
`;
const addTodo = (text: string) => {
addTodo({ variables: { type: text } });
}
const [addTodo] = useMutation(ADD_TODO, {
update(cache, { data: { addTodo } }) {
console.log('MUTATION DATA IS ', addTodo);
}
});
The above console.log displays undefined always whereas in the Network tab I use the query being executed successfully. The documentation says that update function is passed a cache object and the result of the mutation addTodo but for me the result of the mutation is undefined. What am I doing wrong?
Couple of things to pay attention to:
addTodo('Placeholder') : undefined; this syntax looks weird. Considering it is a typo for the purpose of showing the example here on stackoverflow.
your mutation expects text as a variable:
const ADD_TODO = gql`
mutation AddTodo($text: String!) {
addTodo(text: $text) {
id
text
}
}
`;
while you pass variable type when calling mutation:
addTodo({ variables: { type: text } });
try passing text:
addTodo({ variables: { text } });

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'}})}
/>

GraphQL and Apollo - Multiple Mutations

I'm working on a React app that is using Auth0, Hasura/PostgreSQL, GraphQL and Apollo and I'm very green so I obviously need some help. Below is what I'm trying to achieve:
A user submits the form to create a new team. The record is added to 'teams' table and now I need to return that Id so I can create a row inside 'teamstaff' table.
Table Structures:
Users
Id
Name
auth0_id
Teams
Id
Name
Created_By
Teamstaff
Id
User_Id
Team_Id
Role_Id
import gql from "graphql-tag";
const insertTeam = gql `
mutation ($name: String!, $gender: String!, $birth_year: Int!, $created_by: String!) {
insert_teams(objects: {name: $name, gender: $gender, birth_year: $birth_year, created_by: $created_by}) {
affected_rows
returning {
id
name
gender
birth_year
created_by
}
}
}
`;
export default insertTeam;
I'm able to add a new team to the DB but I need help on getting the Id from that newly created team so I can create the initial record in the 'teamstaff' table. Also, is there a better way of structuring my tables? Each user can be assigned to multiple teams and different roles for each team.
I'm not sure how you're performing this mutation, but I'll assume that you're using Apollo's Mutation Component. This is an example of how you could get the ID of the recently added record:
import React from "react";
import gql from "graphql-tag";
import { Mutation } from "react-apollo";
const INSERT_TEAM = gql `
mutation InsertTeam($name: String!, $gender: String!, $birthYear: Int!, $createdBy: String!) {
insertTeam(objects: {name: $name, gender: $gender, birthYear: $birthYear, createdBy: $createdBy}) {
affectedRows
returning {
id
name
gender
birthYear
createdBy
}
}
}
`;
const onInsertTeamCompleted = ({ insertTeam }) => {
console.log(insertTeam.returning.id); // Here you have your ID
}
const Screen = () => (
<Mutation mutation={INSERT_TEAM} onCompleted={onInsertTeamCompleted}>
{(insertTeam, { data }) => { // Through data, you can also access data.insertTeam results.
const onInserTeam = () => {
insertTeam({ variables: {name: "Mary", gender: "Female", birthYear: 1990} });
};
return (
<button onClick={onInserTeam}>Insert demo team</button>
);
})}
</Mutation>
)
export default Screen;
As you might have noticed, I've updated your query to follow the naming conventions for attributes (yep, using camelCase), but this change has no impact on the final result.
If you've not read it already, the Mutation Component section in Apollo docs talks about a lot of important things like updating the cache and handling errors, so it's a must-read! 😉
I know this question is old, but Hasura will handle this for you (at this point).
You just need to supply one side of the relationship with the User_Id field
https://docs.hasura.io/1.0/graphql/manual/mutations/insert.html#insert-an-object-along-with-its-related-objects-through-relationships
mutation($name: String!, $gender: String!, $birth_year: Int!, $created_by: String, $user_id: String!) {
insert_teams(
objects: {
TeamStaff: {
data: {
User_Id: $user_id
}
},
name: $name,
gender: $gender,
birth_year: $birth_year,
created_by: $created_by }
) {
affected_rows
returning {
id
name
gender
birth_year
created_by
}
}
}

GraphQL Return Query Result as an Array

I have been following the React-Apollo and Node.js GraphQL Tutorials on https://www.howtographql.com/ and was able to get a demo up and running.
What I would like to do now is return the result of my query as an array.
My schema.graphql file looks like this:
type Query{
pullTickets (where: TicketWhereInput): [Ticket!]!
}
And the resolver looks like:
const resolvers = {
Query: {
pullTickets: (root, args, context, info,) => {
return context.db.query.tickets({}, info)
}
}
}
What I have tried so far is:
import React, { Component } from 'react';
import Query from "react-apollo/Query";
import gql from "graphql-tag";
const GET_TICKETS = gql`
query getTickets($startDate: DateTime!, $endDate: DateTime!) {
pullTickets (where: {
AND:[{DateCloseDate_gt: $startDate}, {DateCloseDate_lt: $endDate}]})
{
id
}
}
`;
export default function GetTickets ( startDate, endDate ) {
var temp = [];
<Query query={GET_TICKETS} variables={{ startDate, endDate }} >
{({ loading, error, data }) => {
if (loading) return 'Loading...';
if (error) return `Error!: ${error}`;
// This doesn't seem to do anything
temp = data.pullTickets
}}
</Query>
// temp is showing up as "undefined" in the console
console.log(temp);
return temp
}
I should be getting a list of Tickets but I am getting undefined.
How to use client.query or client.mutation without using jsx
I had the same issue, I wanted to use query without using any jsx, the solution is to use ApolloClient, at some point in your app you will use ApolloProvider which u will need to give it an instance of ApolloClient as a prop, all u have to do is export that client and u can then use it anywhere else not only in the ApolloProvider.
Here is an example
initApollo.js
this is where Apollo client is initialized.
import { ApolloClient } from 'apollo-client';
.
.
.
initApolloClient ({ uri }) => {
.
.
.
return new ApolloClient({
link,
cache,
});
}
export default initApolloClient
useClientWithoutJsx.js
import initApollo from './initApollo';
client = initApollo({ uri: 'http://localhost:4000' });
client.query(({query: SOME_QUERY, variables: {id: 2}) => {
// return data
})
does this answers your question ?

Resources