Syntax Error: Invalid number, expected digit but got: "t". while passing a slug url to the graphql query function (nextjs app)

Viewed 157

I'm having this error while I'm trying to get the right content according to the url. This is my query function:

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

  return SLUG_QUERY;
};

my getStaticprops where I pass the context.params.id:

export const getStaticProps = async (context) => {
  const apolloClient = initializeApollo();
  const { data } = await apolloClient.query({
    query: getSlugQuery(context.params.id)
  });

and the getStaticPath to prerender the cases:

export async function getStaticPaths() {

  const apolloClient = initializeApollo();
  const { data } = await apolloClient.query({
    query: POSTS_QUERY
  });

  const paths = data.postCollection.items.map((post) => ({
    params: { id: post.slug },
  }))

  return { paths, fallback: false }
}

If I try to pass an hardcoded url to the query, the response is working. What am I doing wrong there? thanks

1 Answers

I believe you need to change your implementation to pass variables

Change getSlugQuery to not take any parameters:

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

  return SLUG_QUERY;
};

Then change getStaticProps to pass the slug as a variable to the apolloclient:

export const getStaticProps = async (context) => {
  const apolloClient = initializeApollo();
  const { data } = await apolloClient.query({
    query: getSlugQuery(),
    variables: {
      slug: context.params.id,
    },
  });
};
Related