Sup guys. I'm learning Apollo GraphQL with React, and i just made a project consuming and open API (only using GET) Facing my final problem before i can deploy my application: "undefined" data when i try to GET using an ID (Int).
Github Repo: https://github.com/akzeitions/reactbeer
My Query (works at GraphiQL):
const CERVEJA_QUERY = gql`
query CervejaQuery($id: Int!){
cerveja(id : $id){
id
name
tagline
image_url
abv
ibu
}
}
`;
console.log(CERVEJA_QUERY);
Probably the problem: Resolve
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields:{
cerveja: {
type: new GraphQLList(CervejaType),
args: {
id : {type : GraphQLInt}
},
resolve(parent, args) {
return axios
.get(`https://api.punkapi.com/v2/beers/${args.id}`)
.then(res => res.data);
}
},
export class CervejaDetalhe extends Component {
render() {
//get and parse ID
let { id } = this.props.match.params;
id = parseInt(id);
return (
<Fragment>
<Query query={CERVEJA_QUERY} variables={{ id }}>
{
({ loading, error, data }) => {
if (loading) return <h4>Carregando...</h4>
if (error) console.log(error)
const {
name,
tagline,
image_url,
abv,
ibu
} = data;
//undefined :(
return (
<div>
<h1 className="display-4 my-3">
Cerveja : {name}
</h1>
</div>
Just lost some hours reading, making tests and trying to figure out without success. :(
The issue seems to be in your server implementation.
Your type ceveja
is returning a list type: new GraphQLList(CervejaType)
but you are expecting to get only one record instead of a List.
Also, the api api.punkapi.com/v2/beers/${args.id}
returns an array (List
) so you should transform it into a object as well.
You should change your RootQuery
into something like:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields:{
cerveja: {
type: CervejaType, // HERE: remove the List
args: {
id : {type : GraphQLInt}
},
resolve(parent, args) {
return axios
.get(`https://api.punkapi.com/v2/beers/${args.id}`)
.then(res => {
// HERE: you need to transform the data from the API into
// one object instead of an array
const [data] = res.data
return data
});
}
},