Home > other >  Get the data from GraphQL query in React
Get the data from GraphQL query in React

Time:10-09

I'm sorry if this is something obvious, I just don't get it. I'm trying to get data from GraphQL server. I'm following the docs on Apollo client and everything's fine. The problem is that I keep getting the data in the form of a promise, rather than a real object

const GET_DATA = gql`
  {
    category {
      name
      products {
        name
        inStock
      }
    }
  }
`;
const data = client
  .query({
    query: GET_DATA,
  })
  .then((result) => {
    return result;
  })
  .then((res) => res.data);
ReactDOM.render(
  <ApolloProvider client={client}>
    <React.StrictMode>
      <App data={data} />
    </React.StrictMode>
  </ApolloProvider>,
  document.getElementById("root")
);

I tried chaining another .then() method and converting the response with .json() method, it didn't work. Maybe because GraphQL responses are different?

I would use useQuery() hook but I'm specifically asked to work with Class Components

CodePudding user response:

That data const variable will hold a promise, but the result you get from GraphQl should be the correct one, in the first .then block you need to save the result in a state, then return that state as data to your App component.

  • Related