0

I'm new to graphql and i'm trying to find a single fish by the name I pass into the query. I feel like what I have is close, but it is still returning null in the query and I'm not sure why. Any help would be appreciated!

Here is the dummy data I have in memory:

const fish = [
    { id: 1, name: 'bitterling', available: ['march', 'april', 'may'], amountCaught: 0, sellingPrice: 200 },
    { id: 2, name: 'black bass', available: ['june', 'july', 'august'], amountCaught: 123, sellingPrice: 1000 },
    { id: 3, name: 'koi', available: ['march', 'april', 'feburary'], amountCaught: 12, sellingPrice: 4000 }
]

Schema:

     type Query {
         fish: [Fish!]!
         singleFish(name: String): Fish
     }

     type Fish {
         id: ID!
         name: String!
         available: [String]
         amountCaught: Int
         sellingPrice: Int
    }

Resolvers:

const resolvers = {
    Query: {
        fish: () => fish,
        singleFish: (parent, args) => fish.filter(i => i.name === args.name)
        }
    }
}

Query in graphiql:

{
  singleFish(name: "bitterling") {
    amountCaught
  }
}

Result:

{
  "data": {
    "singleFish": {
      "amountCaught": null
    }
  }
}
fev3r
  • 79
  • 6
  • 1
    fish.filter(....)[0] ? – xadm May 12 '20 at 21:10
  • ahh okay, that works. I get why it was working too. It returned an array with one item in it, which is why the values were all null. I'm sure there's a better way of writing what I have. – fev3r May 12 '20 at 21:16
  • 1
    resolver has to return a fish typed object, returning anything other (array/string/int) results with null .... you can use any filtering method that returns one object – xadm May 12 '20 at 21:29
  • 1
    See [Common Scenario #2](https://stackoverflow.com/a/56319138/6024220). You could use `find` instead of `filter` -- that returns the first matching item from the array or `undefined` if one cannot be found. – Daniel Rearden May 12 '20 at 21:29
  • got it, thanks for your help. both good input. – fev3r May 12 '20 at 21:34

0 Answers0