0

I'm working on a react app. I want to use this query :

const Newss = gql`
  query getNewssData {
    newss(ordered: true) {
      id
      title
      content
      event{
        id
        title
      }
    }
  }
`;

executed by this react code :

<Query query={Newss}>
  {({ loading, error, data }) => {
    if (loading) return LoadingNews();
    if (error) return `Error! ${error.message}`;
    return data.newss.map(news => newssToRender(news));
  }}
</Query>

But it return Error! because there are some news without event. How to permit to do this query sometimes even if event could be null ?

Thank you very much for your help !

Izaya

Note :

function newssToRender(news) {
  if (news.event === null) {
    return newssToRenderWithoutEvent(news);
  }
  return (
    <div>
      <News
        title={news.title}
        content={news.content}
        eventid={news.event.id}
        eventTitle={news.event.title}
        pictureSrc={news.picture}
      />
    </div>
  );
}

2 Answers 2

1

The error indicates the field is a Non-Null type, which is a special type in GraphQL that wraps another type. Non-null fields cannot return null and will cause an error if they do. This is no different than a field being declare an Int and then returning a String -- the wrong type was provided (and couldn't be coerced) so an error is thrown.

A schema is a contract for server-client communication. If a field is of a specific type, the server effectively guarantees that the field will always be that type. This limits the work on the client, as it eliminates the need for type-checking the response on the client-side.

Unfortunately, there's not much you can do because such errors represent an issue with the server-side code itself. If it makes sense for the event to be sometimes null, then the field should be made nullable. Otherwise, whatever underlying code should be fixed to prevent the field from ever returning null. The proper course of action is to file a bug with the author of the API (or fix the code yourself if that's you!).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. It's really much clear for me now. I was thinking that there was a schema.gql issue but in fact it comes from the gateway loader.
1

It was indeed a gateway issue :

event: (root, args, context) => context.loaders.event.load(root.event)

replaced by :

event: (root, args, context) => root.event ? context.loaders.event.load(root.event) : null,

to allow null value

Thank you Daniel

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.