Sam Roehrich
Sam Roehrich

Reputation: 123

Graphql error when finding object. Can not assign null to non nullable field

I have been playing with the simple problem for days now and can not figure out my error. I am trying to return one object from an array of object with the object id.

playground query

schema definition

type Query {
info: String
feed: [Link!]
link(id: String!): Link
}

type Mutation {
post(url: String!, description: String!): Link!
updateLink(id: ID!, url: String!, description: String!): Link!
deleteLink(id: ID!): Link!
}

type Link {
id: ID!
description: String!
url: String!
}

index.js

const { GraphQLServer } = require('graphql-yoga');

let links = [{
id: 'link-0',
url: 'www.howtographql.com',
description: 'Fullstack tutorial for GraphQL',
author: 'sam roehrich'
}]

let idCount = links.length

const resolvers = {
Query: {
info: () => `This is the API of a Hackernews Clone`,
feed: () => links,
link: (parent, {id}) => {
  return links.filter(link => {
    link.id === id
  })
}
}

Upvotes: 2

Views: 400

Answers (2)

Nikitas IO
Nikitas IO

Reputation: 1181

Way late to the party, but I thought I'd give a clear answer to this question for others in a similar situation.

Daniel Rearden in the comments is right. Basically, the problem is that the filter() function returns an array instead of an Object. A simple solution to this problem would be to return the first (and only) item of the array in the resolver:

const link = links.filter(link => {
    link.id === id
})
// Return only the first link from the array.
return link[0];

Upvotes: 2

King Strips
King Strips

Reputation: 11

filter returns a new list that satisfy the given condition, so you're returning a list than an item(object) of the list

Upvotes: 0

Related Questions