Delete and Update Graphql mutation in Amplify ReactJs - graphql

Amplify automatically generates mutations for delete like this:
export const deleteTodo = /* GraphQL */ `
mutation DeleteTodo($input: DeleteTodoInput!) {
deleteTodo(input: $input) {
index
body
hasRead
}
and this is how I call it in my App.js
await API.graphql(graphqlOperation(mutations.deleteTodo, {input: result}));
It returns an error like this. Seems like the data has not been passed
message: "The variables input contains a field name 'index' that is not defined for input object type 'DeleteTodoInput' "

I'm not sure what result is but you can try:
const result = {
index: 1,
body: 'blabla',
hasRead: true,
}
await API.graphql(graphqlOperation(mutations.deleteTodo, {input: { ...result }}));

Problem is with the result variable. It should be {result} and it should have the index. Incase you dont have index remove it from the query
const deleteTodo = /* GraphQL */ `
mutation DeleteTodo($input: DeleteTodoInput!) {
deleteTodo(input: $input) {
body
hasRead
}
await API.graphql(graphqlOperation(mutations.deleteTodo, {input: {result}));

Related

Graphql apollo-client useMutation variable with gql , GraphQLInputObjectType does not check for input object fields

could anyone please help me understand on how to validate the input argument object type on apollo client , i am trying to make sure that passing additional fields on the input object fails the query . But it works even if i pass additional fields (Note : I want the validation on front end and not on the server)
const mutationInput = new GraphQLObjectType({
name: 'mutationInput',
fields: {
Id: String,
statusCode: String,
}
});
const GET_DATA = gql`
mutation($in: ${mutationInput}!){
getData(in: $in) {
status
}
}
}`;
//usage
const [getData, { error,loading }] = useMutation(
GET_DATA,
{
...
}
)
getData({
variables: {
in: {
statusCode:"OK",
ID:"azz12",
extraField:"some value" //Validation needs to fail as this field is not defined on input object, but never fails on front end
}
}

Passing a variable to GraphQL mutation using ApolloClient doesn't seem to work

I'm trying to figure out how to run mutations using Apollo Client.
Here's the mutation I'm trying to run:
export const CREATE_POST = gql`
mutation CreatePost($title: String) {
createPost(
title: $title
body: "Test body, whatever..."
) {
title
body
slug
}
}
`
Here's the functional component that renders a form, and tries to run this mutation once I submit the form:
export default function post() {
const [createPost] = useMutation(CREATE_POST)
async function handleSubmit(event) {
event.preventDefault()
const { data } = await createPost({
variables: { title: "test title" }
})
}
return (<rendering the form here>)
}
I'm getting an error:
[GraphQL error]: Message: Variable "$title" of type "String" used in position expecting type "String!".
If I remove the $title variable from here: mutation CreatePost($title: String) {, the error disappears. It seems like I'm failing to pass it the variable. But as far as I can tell, this part of the code is correct:
const { data } = await createPost({
variables: { title: "test title" }
})
That's how you're supposed to pass variables to mutations, right? What am I doing wrong? How can I debug this?
The full code for the component is here
Query code is here
Solved it thanks to #xadm.
Had to use mutation CreatePost($title: String!) instead of mutation CreatePost($title: String).

Post data to a graphql server with request-promise

I'm using the request-promise library to make http request to a graphql server. To achieve a query, I'm doing this:
const query = `
{
user(id:"123173361311") {
_id
name
email
}
}
`
const options = {
uri: "http://localhost:5000/graphql",
qs: { query },
json: true
}
return await request(options)
The above code is working fine. However I'm confused about how to go about a mutation since I need to specify both the actual mutation and the inputData like this:
// Input
{
name: "lomse"
email: "lomse#lomse.com"
}
const mutation = `
mutation addUser($input: AddUserInput!){
addUser(input: $input) {
_id
name
email
}
}
`
const option = {
uri: "http://localhost:5000/graphql",
formData: {mutation},
json: true,
// how to pass the actual data input
}
request.post(option)
Or is it that the request-promise library isn't designed for this use case?
Use body, not formData. Your body should consist of three properties:
query: The GraphQL document you're sending. Even if the operation is a mutation, the property is still named query.
variables: A map of your variable values serialized as a JSON object. Only required if your operation utilized variables.
operationName: Specifies which operation to execute. Only required if your document included multiple operations.
request.post({
uri : '...',
json: true,
body: {
query: 'mutation { ... }',
variables: {
input: {
name: '...',
email: '...',
},
},
},
})
The graphql-request library seems to do what I needed the request-promise library to do.
import { request } from 'graphql-request'
const variables = {
name: "lomse",
email: "lomse#lomse.com"
}
const mutation = `
mutation addUser($input: AddUserInput!){
addUser(input: $input) {
_id
name
email
}
}
`
response = await request(uri, mutation, {input: variables})

Query variables not being passed down from vue component in apollo

I have a simple query which takes in an ID parameter, but it is not working. It says "TypeError: Cannot read property 'taskId' of undefined" . So I think it does not recognize the 'this' keyword for some reason.
Please take a look:
Apollo query from frontend component:
getCommentsByTask: {
query: GET_COMMENTS_BY_TASK,
variables: {
taskId: this.taskId
},
result({ data }) {
this.getComments = data;
console.log("data", data);
}
}
Defined the query in frontend:
query GET_COMMENTS_BY_TASK($taskId: ID!) {
getCommentsByTask(taskId: $taskId) {
id
parentId
ownerId
text
}
}
Resolver in server:
async getCommentsByTask (_, {taskId}, context) {
const userId = getUserId(context)
const user = await User.findById(userId)
if (!user) return
const comments = await Comment.findById(taskId)
return comments
}
Schema:
type Query {
getCommentsByTask(taskId: ID!): [Comment]
}
Assuming that's a smart query, variables should be a (regular, non-arrow) function if you need access to this.

Error writing result to store for query. Cannot read property 'query' of undefined

I'm getting an error when writing a query to store after a mutation. The mutation works and i'm able to read the query post mutation. When i write the same query to the store cache i get the following Error:
index.js:2178 Error: Error writing result to store for query:
query ($applicationId: Int) {
vApplicationApprovalChainList(ApplicationId: $applicationId) {
id
approvalOrder
approverId
name
applicationId
__typename
}
}
Cannot read property 'vApplicationApprovalChainList' of undefined
at writeToStore.js:101
at Array.forEach (<anonymous>)
at writeSelectionSetToStore (writeToStore.js:97)
at writeResultToStore (writeToStore.js:75)
at InMemoryCache../node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.write (inMemoryCache.js:99)
Here is my code.. the mutation and store.readQuery works but the store.writeQuery gives above error. Thank you in advance for any feedback.
APPROVERSLIST_QUERY = gql`
query ($applicationId:Int){
vApplicationApprovalChainList(ApplicationId:$applicationId){
id
approvalOrder
approverId
name
applicationId
}
}
`;
handleClick() {
const { row, mutate} = this.props;
mutate({
variables: {
id: row.id
},
update: (store, { data: { deleteApprover } }) => {
const newdata = store.readQuery({
query: APPROVERSLIST_QUERY,
variables: { applicationId: row.applicationId }
});
console.log(newdata);
newdata.vApplicationApprovalChainList = newdata.vApplicationApprovalChainList.filter(approver => approver.id !== deleteApprover.id);
store.writeQuery({
query: APPROVERSLIST_QUERY, newdata });
}
});
}
You're not passing in the new data to writeQuery. The object passed to writeQuery must have a property named data containing the new data. Additionally, since your query contains variables, you will need to include that information as well.
store.writeQuery({
query: APPROVERSLIST_QUERY,
data: newdata,
variables: {
applicationId: row.applicationId,
},
});
Please see the official docs for more examples and a more thorough explanation of the two methods.

Resources