javascriptreactjsgraphqlrelayjsrelay

How to determine if relay query is empty or not loaded


I'm using Reactjs and Relay. I want to create something if "this" item is not created yet / array is empty. somehow, the relay query returns an empty array if the data has not been loaded, therefore it keeps created "this item" since it's considered empty. how do we determine if relay query data is actually empty or not loaded / pending?

i.e query:

QueryRenderer(MyComponent, {
    query: graphql`
      query MyComponentQuery($id: ID!) {
        items(containerId: $id) {
          id
          title
        }
      }
    `,
    vars: ({ containerId }) => ({
      id: containerId
    })
  })

handle create "this" item:

useEffect(() => {
    if(!props.items){
      // Create "this" item
    }
}, [props.items]);


Solution

  • I am guessing from your snippet that QueryRenderer is an HOC you are using wrapping relay's QueryRender component?

    If so, this is how you normally determine if a query is in loading state:

    // Example.js
    import React from 'react';
    import { QueryRenderer, graphql } from 'react-relay';
    
    const renderQuery = ({error, props}) => {
      if (error) {
        return <div>{error.message}</div>;
      } else if (props) {
        return <div>{props.page.name} is great!</div>;
      }
      return <div>Loading</div>;
    }
    
    const Example = (props) => {
      return (
        <QueryRenderer
          environment={environment}
          query={graphql`
            query ExampleQuery($pageID: ID!) {
              page(id: $pageID) {
                name
              }
            }
          `}
          variables={{
            pageID: '110798995619330',
          }}
          render={renderQuery}
        />
      );
    }
    

    This snippet is taken from the relay.dev docs.

    Notice how the render renderProp is getting the props field once the query is no longer loading.

    If you are using the new hooks-api, it will be different based on which of the query-hooks you are using.