Joff
Joff

Reputation: 12197

React + Typescript + GraphQL: what to do with null

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>
)

Upvotes: 0

Views: 405

Answers (1)

eskawl
eskawl

Reputation: 637

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

Upvotes: 1

Related Questions