reactjs – Make conditional GraphQL request based on node type value in React component with Apollo Client

I am using React and Apollo Client.

Based on a node type value (nodes.type) from a GraphQL response, I want to conditionally make a GraphQL request to either below query NodeTypeOne or NodeTypeTwo.

// MyBlock.gql

export default gql`
  query NodeTypeOne {
    getNodesOne {
      nodes {
        id
        type
        title
      }
    }
  }
`;

export default gql`
  query NodeTypeTwo {
    getNodesTwo {
      nodes {
        id
        type
        title
      }
    }
  }
`;

So in below React component I want to conditionally make a GraphQL request based on the node type value.

import MyQuery from './MyBlock.gql';

const MyBlock = ({ data: myType }: Props) => {
  const { data } = useQuery<GqlRes>(MyQuery);

  const items =
    data?.items?.map((node) => {
      return {
        id: node.id,
        title: node.title,
      };
    }) || [];

  return data?.items?.length ? (
    <Slider items={items} />
  ) : null;
};

export default MyBlock;

How do I do this in a clean efficient way?

Read more here: Source link