Reputation: 375
I've dummy data (books) which I want see from graphiql gui. But when I use a forEach
loop to iterate through the books, looking for a specific id
, it's returning undefined values, but if I use a normal for
loop it works fine.
This is my code:
let books = [
{ name: 'Name of the Wind', genre: 'Horror', id: '1', authorID: '3' },
{ name: 'The Final Empire', genre: 'Fantasy', id: '2', authorID: '1' },
{ name: 'The Long Earth', genre: 'Sci-Fi', id: '3', authorID: '2' },
];
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLString } },
//this forEach is not working
resolve(parent, args){
books.forEach( function(book) {
if(book.id == args.id) {
console.log(book);
return book;
}
});
}
}
}
});
When I print out the book data, it's showing that particular book in the console but not in the GUI response:
request:
{
book(id: "2") {
name
genre
}
}
response:
{
"data": {
"book": null
}
}
Upvotes: 1
Views: 280
Reputation: 351278
A return <value>
in a forEach
callback is meaningless. The returned value goes nowhere, and the loop is not interrupted either.
Instead use .find
:
return books.find(function(book) {
return book.id == args.id;
});
When performance is important, and you have lots of books, then it is better to first preprocess the books and create a Set:
let books = [
{ name: 'Name of the Wind', genre: 'Horror', id: '1', authorID: '3' },
{ name: 'The Final Empire', genre: 'Fantasy', id: '2', authorID: '1' },
{ name: 'The Long Earth', genre: 'Sci-Fi', id: '3', authorID: '2' },
];
let bookIds = new Set(books.map(({id}) => id));
... and then no loop is needed to know whether a book ID is valid or not:
return bookIds.has(args.id);
Upvotes: 3