简体   繁体   中英

Get the data from GraphQL query in React

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM