How to show Astro component based on a certain field and map the correct data and Astro component in the dynamic slug page

How to show Astro component based on a certain field and map the correct data and Astro component in the dynamic slug page


0

I am using Astro, GraphQL (Apollo Client), Typescript and React.

For now I think don’t need React yet.

I have a dynamic route:
[...slug].astro

I have the following query:

export default gql`
  query Page($pageTarget: String!) {
    page(pageTarget: $pageTarget) {
      type
      content {
        ... on PageOne {
          id
          title
        }
        ... on PageTwo {
          id
          title
        }
      }
    }
  }
`;

In the end this query will become really big so I like to split up things.

I want to create 2 components:
components/PageOne/PageOneContent.astro
components/PageTwo/PageTwoContent.astro

Where e.g. PageOneContent.astro will be something like this:

---
import { client } from '../../utils/graphql';
import GET_PAGE from './PageOneContent.gql';

interface Data {
  page: {
    type: string;
    content: {
      title: string;
    };
  };
}

const uri = `/${Astro.params.uri}`;

const { data, loading } = await client.query<Data>({
  query: GET_PAGE,
  variables: {
    pageTarget: uri,
  },
});
---

<div>
  {loading && <p>Loading...</p>}
  {
    !loading && <h1>Title: {data.page.content.title}</h1>
  }
</div>

Note: Inside PageOne.gql I am querying only for the PageOne fragment like:

export default gql`
  query Page($url: String!) {
    page(url: $url) {
      type
      content {
        ... on PageOne {
          title
        }
      }
    }
  }
`;

What is a clean way to map over this and make it generic so inside [...slug].astro, based on the type field I can show PageOneContent.astro or PageTwoContent.astro?


Load 4 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *