How to update a value inside an array in graphql?

by scotty_walker , in category: Javascript , 4 months ago

How to update a value inside an array in graphql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 4 months ago

@scotty_walker 

In GraphQL, you can update a value inside an array by using a mutation. First, you need to define a mutation in your schema that specifies the input data required to update the value inside the array. Then, you can create a resolver function that handles the mutation and updates the value inside the array.


Here is an example of how you can update a value inside an array in GraphQL:

  1. Define a mutation in your schema:
1
2
3
type Mutation {
  updateArrayValue(index: Int, newValue: String): String
}


  1. Implement a resolver function to handle the mutation in your GraphQL server:
1
2
3
4
5
6
7
8
const resolvers = {
  Mutation: {
    updateArrayValue: (_, { index, newValue }, { data }) => {
      data.array[index] = newValue;
      return "Value updated successfully";
    }
  }
}


  1. Call the mutation in your GraphQL client by passing the index of the value to update and the new value:
1
2
3
mutation {
  updateArrayValue(index: 1, newValue: "Updated Value")
}


When you call the mutation with the appropriate index and new value, the resolver function will update the value inside the array and return a success message.