Unfortunately, I haven't been working with Typescript and GraphQL in combination for long.
The problem I can't solve is that I have an array of objects and I want to do a GraphQL mutation with each of them.
The array looks like this:
(3) [{…}, {…}, {…}]
0: {__typename: 'user', id: '8', name: 'Tom', status: 'active', model: '11045779', …}
1: {__typename: 'user', id: '7', name: 'Mike', status: 'active', model: 'SIJY_B_3', …}
2: {__typename: 'user', id: '5', name: 'Peter', status: 'active', model: 'VS247HR', …}
I want to perform the following function with each object in the array:
async function updateUser(values: ValuesType) {
await updateUser({
variables: {
id: values.user.id,
status: "inactive",
},
});
}
With single objects I can use the function without any problems, but unfortunately I haven't found a way to iterate over an array with it.
The answer is probably simple but somehow none of my attempts were successful.
Is there a simple solution to run this function with every object in the array?
Promise.all or Promise.allSettled are idiomatic approaches to awaiting multiple async functions at once. These standard javascript functions take an array of Promises and return an array of results.
The pattern works works for all async functions. It is not GraphQL specific. Playground here
// sample type
interface ValuesType {
id: String
name: String
status: String
model: String
}
// sample data
const updates: ValuesType[] = [{id: '8', name: 'Tom', status: 'active', model: '11045779'},
{id: '7', name: 'Mike', status: 'active', model: 'SIJY_B_3'},
{id: '5', name: 'Peter', status: 'active', model: 'VS247HR'}]
// a mock update function - with delay to simulate the GraphQL network call
async function updateUser(values: ValuesType): Promise<String> {
return new Promise<String>((resolve) => setTimeout(()=> resolve(values.id), 300))
}
// the important stuff - run the 3 mutations at once
(async ()=> {
// Option 1: Promise.all
const all = await Promise.all(updates.map(updateUser))
console.log('Promise.All result', all) // ["8", "7", "5"]
// Option 2: Promise.allSettled
const allSettled = await Promise.allSettled(updates.map(updateUser))
console.log('Promise.AllSettled result', allSettled) // [{"status": "fulfilled", "value": "8"} ...]
})()