Undistraction
Undistraction

Reputation: 43589

Using GraphQL values with React When They Might Be null

It seems that when a value isn't found in a GraphQL query, it sets that field to null not undefined (See issue here).

null is the undefined or None of GraphQL

Given that React won't use a default prop for a null value, what is the best way to handle the situation where GraphQL data is being passed into a React Component.

For example I have a TagList component into which I am passing the result of a GraphQL query. Although I have the following:

TagList.defaultProps = {
  tags: [],
}

If the query returns no tags, the value of tags will not be undefined, but null, so the default value isn't applied, and the component tries to render using null as the value of tags.

Obviously I can add a check at the top of the render method and set the value to [], but it feels like there must be a better solution.

Upvotes: 3

Views: 1793

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

The GraphQL spec doesn't include a concept of an undefined value -- values are simply either null or non-null. In fact, when outlining the steps for resolving a field's value, it specifies undefined should be coerced into a null value:

If result is null (or another internal value similar to null such as undefined or NaN), return null.

That said, off the top of my head, there's a few ways you could solve this:

1.) On the client side, create a small HOC that you can wrap your components in:

const UndefinedToNull = (Component) => (props) => {
  const newProps = props.map(p => p === null ? undefined : p)
  return <Component {...newProps}>
}

2.) If you're using Apollo as a client, you should be able to create a middleware link that converts null to undefined. Something like:

const middlewareLink = new ApolloLink((operation, forward) => {
  return forward(response).map(result => {
    // transverse the result, mutating it as needed
    return result
  })
}

3.) On the server side, if you're using apollo-server, you can use the formatResponse configuration option to transverse the GraphQL response and convert nulls or undefined as needed. YMMV with other GraphQL middleware.

Upvotes: 2

Related Questions