Home > Software design >  Fetch GraphQL data based on variable
Fetch GraphQL data based on variable

Time:09-29

I am trying to get my query to react to a ref property.

https://v4.apollo.vuejs.org/guide-composable/query.html#variables This wont work at all

   const { result, variables } = useQuery(gql`
      query {
        episodes(page: $page) {
          info {
            pages
            count
          }
          results {
            name
          }
        }
      }
    `, {
      page: 2
    });

Tried this as well

setup() {
    const currentPage = ref(1);
    const { result } = useQuery(gql`
      query {
        episodes(page: ${currentPage.value}) {
          info {
            pages
            count
          }
          results {
            name
          }
        }
      }
    `);
      function pageChange() {
        currentPage.value  = 1;
        console.log(currentPage.value)
    }
    return { result, currentPage, pageChange };
  },

This code below works for me when I input page number manually, but I want to pass the page number as variable, because my pagination page increases and I want the query to refresh.

    const { result, loading } = useQuery(gql`
      query {
        episodes(page: 2) {
          info {
            pages
            count
          }
          results {
            name
          }
        }
      }
    `,  
    );

Can someone assist me?

CodePudding user response:

In the link you gave query is followed by the query name.

const { result } = useQuery(gql`
  query getUserById ($id: ID!) {
    user (id: $id) {
      id
      email
    }
  }
`, {
  id: 'abc-abc-abc',
})

You don’t specify the query name Try this instead:

   const { result, variables } = useQuery(gql`
      query episodes($page: Int) {
        episodes(page: $page) {
          info {
            pages
            count
          }
          results {
            name
          }
        }
      }
    `, {
      page: 2
    });

I don’t know what’s your schema looks like but I inferred that page is a Int. If it’s not change Int by the page type

  • Related