Search code examples
reactjsreact-nativegraphqlapollo

How to use dynamic graphql (string) from separate page in component React / React-native


I have a react-native functional component that uses Apollo useQuery hook to make some graphql queries. When this component is rendered, it receives an id prop from previous page. So I need to use this id in graphql query dynamically.

I can do it inside of the component easily like this

const query = gql`
  query MyQuery {
    getItems(id: \"${id}\") {
      items {
          name
          price
        }
      }
    }
  `;

  const { loading, error, data } = useQuery(query); 

But I need to put all my graphql queries into separate folders. I couldn't figure out how to send a prop to another page and just receive back the graphql string to use in useQuery hook.

So instead of putting const query to current page where I use 'useQuery', I need to receive it from another page.

I want to do something like this:

import Query from '../queries/itemQuery'

const { loading, error, data } = useQuery(Query(id));

I tried this and similar things:

itemQuery.js

import { gql } from '@apollo/client';
const itemQuery = (id) => { 
    gql`
      query MyQuery {
        getItems(id: ${id}) {
          items {
              name
              price
            }
          }
        }
      `;
export default itemQuery

And in main page where I use 'useQuery':

import Query from '../queries/itemQuery'
const { loading, error, data } = useQuery(Query(id));

When I try to send id from main page to itemQuery.js it doesn't work. I'm getting different errors such as itemQuery is not a function etc. I also tried to make it as a function which returns query but it didn't work. I revised this question. Previous answers was not useful for me, I guess I explained it wrong. This is the first question I'm asking on stackoverflow so you can help me improve, just ask missing parts that I should've explained.


Solution

  • You have to use variables in your query. So pass id as variable in your query and then you can pass id variable value from anywhere in query.

    So, first declare your query in itemQuery.js as following :

    export const GET_ITEMS = gql`
      query getItems($id: String) {
        getItems(id: $id) {
          items {
              name
              price
            }
          }
        }
    `;
    

    Now, import query in your component as pass pass variable as below :

    import { GET_ITEMS } from '../queries/itemQueries';
    
    const { loading, error, data } = useQuery(Query, {
      variables: {id: 'your_id`}
    });
    

    Note that I have used $id: String assuming that your id will be string. But you can use any type as your requirement.