Graphql Schema Issue

System Information

4.1.0- Strapi Version:


Hi,

Just a question about how the schema needs to be presented using graphql.

If I check the docs for Strapi v4 an example query would be as follows:

query Restaurants {
  restaurants {
    id
    name
    description
    categories {
      name
    }
  }
}

The results of this query look like this:

{
  "data": {
    "restaurants": [
      {
        "id": "1",
        "name": "Biscotte Restaurant",
        "description": "Welcome to Biscotte restaurant! Restaurant Biscotte offers a cuisine based on fresh, quality products, often local, organic when possible, and always produced by passionate producers.",
        "categories": [
          {
            "name": "French Food"
          }
        ]
      }
    ]
  }
}

However trying to pull a similar type of post I need to add on extra ‘data and attributes’ layer to the graphql query before I can pull the fields.

query GetLessons {
  lessons {
	data {
      attributes {
        heading
      }
    }
  }
}

This then gives a different structure to the response:

{
  "data": {
    "lessons": {
      "data": [
        {
          "attributes": {
            "heading": "Pentatonic Scale"
          }
        },
        {
          "attributes": {
            "heading": "Mixolydian Scale"
          }
        },
        {
          "attributes": {
            "heading": "Harmonic Minor Scale"
          }
        }
      ]
    }
  }
}

I have the data object, then a lessons object, then the data array. This means on the front end I can’t map through my posts properly. I should just map lessons.data but I can’t as there’s an object nested in an object.

Any idea why this is happening and what I might have done to cause this?

Thanks!

1 Like

I am experiencing the same issue mapping a graphql query using Apollo Client. ex below

const REVIEWS = gql`
  query GetReviews {
    reviews {
      data {
        id
        attributes {
          title
          rating
          body
        }
      }
    }
  }
`;


export default function Homepage() {
  const { loading, error, data } = useQuery(REVIEWS);
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  console.log(data);

  return (
    <div>
      {data.data.reviews.map((review) => (
        <div key={review.attributes.id} className="review-card">
          <div className="rating">{review.attributes.rating}</div>
          <h2>{review.attributes.title}</h2>
          <small>console list</small>
          <p>{review.attributes.body.substring(0, 200)}...</p>
          <Link to={`/details/${review.id}`}>Read more</Link>
        </div>
      ))}
    </div>
  );
}