Using useQuery apollo client to get data by id not working

ntention:

trying to query from apollo client based on dynamic id. Have successfully checked in server provided interface which is working… and trying to do same from the client.

From the doc it looks like i need to use variables which i did.

Problem:

query using variables looks good but i am getting undefined in client.

Query which is working in graphql API:

query abc {
    getCategoryProduct(id:"NzI1NDc1MTM1") {
      id
      title
      description
      favorited
      published
      price_per_day
      price_per_week
      price_per_month
      price_per_weekend
      picture
      pictures {
        id
        url
      }
      createdAt
      updatedAt
    }
  }

Problematic code in client

const GETDETAILS = gql`
  query abc($id: String!) {
    getCategoryProduct(id: $id) {
      id
      title
      description
      favorited
      published
      price_per_day
      price_per_week
      price_per_month
      price_per_weekend
      picture
      pictures {
        id
        url
      }
      createdAt
      updatedAt
    }
  }
`;

const DetailScreen = () => {

  const { loading, error, data } = useQuery(GETDETAILS, {
    variables: { id: "NzI1NDc1MTM1" },
  });

  useEffect(() => {
    if (loading == false) {
      console.log("=====data=====", data);  // DATA IS EMPTY DO NOT NOT WHY??
    } 
  }, [data]);

Hello! If loading is false and data is empty, then error should not be empty. Try logging error to the console to get more information on the error that occurred. You can also check your server’s response in your browser’s network tab.

As an initial thought, it’s possible that the getCategoryProduct field’s id argument is of type String instead of String!. If so, the $id variable’s type needs to be String (instead of String!) as well.

1 Like

I’d start by simplifying what you have to debug. Ditch the useEffect and just log loading, error and data to the console and see whether you get anything…ever. Maybe there’s something with the useEffect hook that isn’t working as you expect…if so, eliminate that for the moment so you can simplify where to look for the issue.

Finally, besides the results of the query that you see in the console…what about the actual network request? Is it returning with the appropriate status code, response structure, and the expected data?

1 Like