Adding an argument to a GraphQL request

335 views Asked by At

I am using React Starter Kit and I'm trying to pass a string along with the query as an argument but nothing works. I have tried the following:

export default {

  path: '/',

  async action() {
    const resp = await fetch('/graphql', {
      method: 'post',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        query: `{
          posts {
            id,
            title,
            content,
            date
          },
          page(slug: 'homepage'){
            id,
            date,
            modified,
            slug,
            type,
            title,
            content,
            excerpt,
            author
          }
        }`,
      }),
      credentials: 'include',
    });
    const { data } = await resp.json();
    console.log('in home/index');
    if (!data || !data.posts) throw new Error('Failed to load the homepage.');
    return {
      title: 'React Starter Kit',
      component: <Layout><Home posts={data.posts} page={data.page} /></Layout>,
    };
  },

};

But it fails every time I include the parens... what is the right way to pass along an argument?

1

There are 1 answers

0
j0e On

The solution to this problem is to correctly setup arguments in the final Query type in the schema, like so:

type Page{
  id: Int
  slug: String
  title: String
  content: String
}

type Query{
  page(slug: String): Page 
}

schema {
  query: Query
}