Search code examples
reactjsgraphqlapolloreact-apolloapollo-client

React / Apollo: Displaying result of GraphQL query (useQuery hook)


I am new to react/graphql/apollo however I have followed the guide on how to do a graphql query using Apollo on www.apollographql.com. However I don't seem to be able to show the result.

This is the code I am executing to do the query

import React from "react";
import { useQuery } from 'react-apollo';
import gql from "graphql-tag";

const GET_PRODUCTS = gql`
  query getProducts{
    products(first: 1) {
      edges {
        node {
          id
          name
        }
      }
    }
}
`;

const StartPage = () => {
  const { loading, error, returnData } = useQuery(GET_PRODUCTS, {
    variables: {},
  });
 
  return (
    <p>Hello world, this should be the data: {returnData}</p>
  );
};

I only see "Hello world, this should be the data:" but the returnData is not printed? Can't I just print the entire response?

When I reload the page I can clearly see in the networks tab that my query does get executed and I get a correct response back

request

{"operationName":"getProducts","variables":{},"query":"query getProducts {\n  products(first: 1) {\n    edges {\n      node {\n        id\n        name\n        __typename\n      }\n      __typename\n    }\n    __typename\n  }\n}\n"} 

response

{"data":{"products":{"edges":[{"node":{"id":"UHJvZHVjdDo3Mg==","name":"Apple Juice","__typename":"Product"},"__typename":"ProductCountableEdge"}],"__typename":"ProductCountableConnection"}}}

So does anyone have an idea why returnData is not printed / is empty?


Solution

  • It should be const { loading, error, data } = useQuery(GET_PRODUCTS, ...); Note: data instead of returnData.

    When you destructure objects, you need to be exact when it comes to the key. If you need the data to live in a variable called returnData, you could do something like this:

    const { loading, error, data: returnData } = useQuery(GET_PRODUCTS, {
      variables: {},
    });
    

    Also be aware that in React you cannot just render objects inside curly braces, React expects a string or a number. For quick debugging you could add

    return (
      <p>Hello world, this should be the data: {JSON.stringify(returnData)}</p
    );
    

    Otherwise you should display data from deep inside the return object.