E
E
Egor Dovydenko2021-09-23 12:58:06
React
Egor Dovydenko, 2021-09-23 12:58:06

How to pass variables to GraphQL query in React components?

Good afternoon. I have a Product component that receives an item id from another component. I need to pass this id to the request to GraphQL and, accordingly, get information about this product.

Here is the request code in Queries.js:

import {gql} from '@apollo/client';

export const CHOOSE_PRODUCT = gql`
    query{
        product(id:"huarache-x-stussy-le"){
            name
            description
        }
    }
`


And this is how I pass it to Product.js:
import { useQuery} from "@apollo/client"
import {CHOOSE_PRODUCT} from "../graphql/Queries"

export default function Product(){

    const {data} = useQuery(CHOOSE_PRODUCT)

    if(data){
        console.log(data)
    }


I've tried some options for passing the value, but nothing has worked so far. How to decide?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
HealSpirit, 2021-09-23
@HealSpirit

import { gql } from "@apollo/client";

export const getChooseProductQuery = (id) => gql`
  query {
    product(id: ${id}) {
      name
      description
    }
  }
`;

import { useQuery } from "@apollo/client";
import { getChooseProductQuery  } from "../graphql/Queries";

export default function Product(props) {
  const { id } = props;
  const { data } = useQuery(getChooseProductQuery(id));

  if (data) {
    console.log(data);
  }
}

This will not work?

E
Egor Dovydenko, 2021-09-24
@Doktorjd

No, it didn't.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question