Search code examples
next.jsgraphqlthegraph

How to use dynamic variables using GraphQL in NEXTjs


So I am trying to build an application in which I need to pass the account as queury. How can I achieve this?

My proposed solution (which is not working obviously):

let account = '0x74c7b157af4E5418F03eb928DF309cc98CE38E66';  
const GET_ACTIVE_ITEM = gql` 
{
   activeFiles(
      first: 5 
      where: {Account_contains: ${account}}
    ) {
       id
       tokenId
       ipfsHash
       Account
       Privilege
      }
}`

Error message I got

enter image description here


Solution

    1. You're missing query
    2. I don't think you can interpolate a variable like that.

    Try to put it in a variable in a query like this:

    const GET_ACTIVE_ITEM = gql` 
    query GetActiveFiles($account: String!) {
      activeFiles(
        first: 5 
        where: {Account_contains: $account}
      ) {
        id
        tokenId
        ipfsHash
        Account
        Privilege
      }
    }`;
    

    And then you can go:

    let account = '0x74c7b157af4E5418F03eb928DF309cc98CE38E66';
    
    const { loading, error, data } = useQuery(GET_ACTIVE_ITEM, {
          variables: {
            account: account
          },
      });
    

    Give this a read: https://www.apollographql.com/docs/react/data/queries/