Roberto Fosso
Roberto Fosso

Reputation: 27

Pass a query url param inside a graphql query (Next js)

I'm trying to get a content by the slug param in the url inside a next js app. When using getServerSideProps, I can pass a context.query.id, but here I'm trying to use getStaticProps. This is what I have so far:

export async function getStaticProps() {
  const apolloClient = initializeApollo();
  const { data } = await apolloClient.query({
    query: SLUG_QUERY,
  });

  return addApolloState(apolloClient, {
    props: {
      data,
    },
    revalidate: 60,
  });
}

const SLUG_QUERY = gql`
  query ($id: String!) {
    postCollection(slug: { eq: $id }) {
      items {
        title
        shortDescription
        heroImg {
          url
        }
        createdAt
        slug
      }
    }
  }
`;

I'm struggling to understand How can I pass the conbtext.query.id as a parameter in the gql query. Thanks for the help

Upvotes: 1

Views: 1650

Answers (1)

Christian Hagelid
Christian Hagelid

Reputation: 8355

pass context into your getStaticProps function

export const getStaticProps = async (context) => {

then move your query inside the getStaticProps to use it

postCollection(slug: { eq: $context.params.id }) {

Alternatively, if you prefer to keep your query outside of the function (if you are reusing it elsewhere for example), then just wrap it in a function that takes the id as a parameter

const getPostCollectionQuery = (id) => {
  const SLUG_QUERY = gql`
    query ($id: String!) {
      postCollection(slug: { eq: $id }) {
        items {
          title
          shortDescription
          heroImg {
            url
          }
          createdAt
          slug
        }
      }
    }
  `;

  return SLUG_QUERY;
};

and then you can call that from your getStaticProps function

const { data } = await apolloClient.query({
  query: getPostCollectionQuery(context.params.id),
});

Upvotes: 3

Related Questions