0

GraphQL queries return a type or null. I'm having trouble coming up with a clean way to handle all these nulls cleanly...

if I have a big nested graphql query...

query {
  markdown {
    authors {
      names {
        first 
      }
    }
  }
}

then each of those fields is nullable up to the top, so then in my TSX file I would have to check those somehow, but how to do it cleanly?

const Component = ({ data }) => (
  <div>
   {data && data.markdown && data.markdown.authors && data.markdown.authors.names && data.markdown.authors.names.first}
  </div>
)
Joff
  • 11,247
  • 16
  • 60
  • 103
  • Too bad optional chaining is not yet a thing, otherwise that's what I would have suggested. `data?.markdown?.authors?.names?.first` anyone? I thought typescript had this feature and it was called `elvis operator`, but it seems I may have misread that – smac89 Jul 02 '18 at 04:59
  • I saw your initial answer and I got excited but it doesn't work like that I think. It only works in declarations as far as I know – Joff Jul 02 '18 at 05:04
  • See this other answer which suggests a way of making use of this operator through babel. https://stackoverflow.com/a/41897688/2089675 – smac89 Jul 02 '18 at 06:15

1 Answers1

1

If you are using lodash, you can use the methods _.get and _.has to determine if the data object has the deeply nested key.

const data = {a: {b: {c: 'nested data'}}}
_.get(data, 'a.b.c') // returns 'nested data'

Also see answers to the following questions for other approaches.

  1. Test for existence of nested JavaScript object key
  2. adding to json property that may or may not exist yet
eskawl
  • 587
  • 1
  • 4
  • 17