I have a Headless cms project I created using GraphQl, NextJS and Hygraph.
I'm also using NPM Graphql-request.
I'm having issues "receiving" more than 10 posts on my project.
So far I had less then 10 posts on my site, but now that I posted more, I'm simply not receiving the extra ones.
I did some research but I can't seem to find the solution!
Here's what I got:
const QUERY = gql`
{
posts {
title
id
slug
datePublished
mobileCoverPhoto {
url
}
coverPhoto {
id
url
}
category
imageAtlTag
author {
id
name
avatar {
url
}
}
content {
text
html
}
}
}
`;
Everything works fine until post #10 only.
Thanks everyone for helping!
10 is the default number of fetched posts. If you want to specify the number of posts you need to do it like this:
posts(first: 10) {
nodes {
title
slug
}
}
Related
I have a already made project having connection between Algolia + Gatsby + Contentful.
In which the algolia queries have
allContentfulProduct {
nodes {
objectID: id
productTitle: title
slug
seoTitle
node_locale
}
}
}
const queries = [
{
indexName: process.env.ALGOLIA_SEARCH_INDEX_NAME_PRODUCTS,
query,
transformer: ({ data }) => data.allContentfulProduct.nodes,
}
]
I need to add one extra field to algolia to filter through the search.
But when i add isVisibleInternalSearch to the const query the field is only visible when the gatsby build command in ran.
When there is any change in the contenful fields then the site is not able to find the algolia field.
allContentfulProduct {
nodes {
objectID: id
productTitle: title
slug
seoTitle
node_locale
isVisibleInternalSearch
}
}
}
I am having the same problem in the example site I created on netlify. Once the site was working fine but when there was any kind of change in contentful the field from the algolia disappeared.
I've just started using Gatsby with the Sanity headless CMS.
For the most part it's pretty straight forward; but knowing best practises for querying the data through GraphQL is still bothering me. How I'm doing it currently is just frantically clicking through my CMS structure in the GraphQL playground and finding what I want. This works but the lack of uniformity in this approach is making me uneasy.
For example, if I want a hero image that's in the CMS somewhere, i'll need to do something like:
query SomePageQuery($id: String) {
sanitySomePage(id: { eq: $id }) {
id
heroImage {
asset {
fluid(maxWidth: 1500) {
...GatsbySanityImageFluid
}
}
}
}
}
But if I want some PortableText block then I need to query the corresponding _raw field of whatever type. So, if my type was introText, Gatsby also provides a _rawIntroText. I'm only able to get the full PortableText from this _raw version of the data. Like this:
query SomePageQuery($id: String) {
sanitySomePage(id: { eq: $id }) {
id
_rawIntroText
}
}
It seems that, for some data you can use [Type], and sometimes you have to use _raw[Type].
There's not a great deal of documentation as to why this is the case. And I'm not sure if this is enforced via Sanity or Gatsby.
My question I guess would be, why does _raw[Anything] exist in the Gatsby and/or Sanity world, and how do people decide on which to use (other than just trial and error within the GraphQL playground and at runtime)?
This is coming from the gatsby-source-sanity plugin that Sanity built and maintains. Hopefully someone from Sanity can provide more context, but effectively the _raw[FieldName] entries return the original JSON data for the field. The unprefixed field (e.g. fieldName) is probably not what you want—it'll only contain bits of metadata about the data.
I tend to pull the _raw[FieldName] data and then just pass it straight into the #sanity/block-content-to-react component like so:
import React from "react"
import { graphql } from "gatsby"
import SanityBlockContent from "#sanity/block-content-to-react"
export default ({ data: { page } }) => (
<SanityBlockContent
blocks={page.textContent}
projectId={process.env.GATSBY_SANITY_PROJECT_ID}
dataset={process.env.GATSBY_SANITY_DATASET}
/>
)
export const query = graphql`
query SomePageQuery($id: String) {
page: sanitySomePage(id: { eq: $id }) {
textContent: _rawTextContent
}
}
`
Note that I'm using GraphQL aliasing to continue to refer to the field as textContent in my component rather than coupling the component to the specifics of this GraphQL schema.
You don't need to use Gatsby Image for Sanity images since they have their own image transformation pipeline anyways. Instead you can just fetch asset { _id } and then use #sanity/client like this to generate an image url:
import sanityClient from "#sanity/client"
import sanityImageUrl from "#sanity/image-url"
const client = sanityClient({
dataset: process.env.GATSBY_SANITY_DATASET,
projectId: process.env.GATSBY_SANITY_PROJECT_ID,
useCdn: true,
})
const builder = sanityImageUrl(client)
builder.image({ _id: "..." }).width(400).dpr(2).url()
Seeing some strange behavior querying a Prismic data source and filtering by a content relationship in my gatsby site. I"m trying to create a page filtering some products based on the category passed into this page. Reading both the Prismic and Gatsby docs, i should be able to filter the data with the where clause but i get this error when i try to build
error Unknown argument "where" on field "allPrismicModel" of type "Query"
Below is the relevant sections of the query
query getProducts($uid: String) {
allPrismicModel(where: { system_category: $uid }) {
edges {
node {
data {
system_category {
uid
}
...other fields here...
}
}
}
}
}
Anybody ever encountered this or know how to resolve it?
where doesn't exist in Gatsby. I'd highly recommend using GraphiQL (under localhost:8000/___graphql) to see what you can do. There is also this doc showing all possibilities: https://www.gatsbyjs.org/docs/graphql-reference/
It'll probably will be in the end (untested):
filter: { system_category: { eq: $uid } }
allPrismicModel(filter: { system_category : { eq: $uid } }) {
edges {
node {
data {
system_category {
uid
}
...other fields here...
}
}
}
}
}
This is a more common way to run that query
I ran into a problem querying a field of type "long text" from contentful.
I know the Contentful long text field is actually markdown. So I installed the gatsby-transformer-remark plugin, which I presumed I need.
Here's my GraphQL query:
query getStoreById($relativeUrl: String!) {
contentfulStore(relativeUrl: { eq: $relativeUrl }) {
relativeUrl
shopPageTitle
mainPageTextContent {
mainPageTextContent
}
}
}
The console still shows:
Objects are not valid as a React child (found: object with keys {childMarkdownRemark}).
Something to do with that error message.
Thanks!
The query will look something like:
query getStoreById($relativeUrl: String!) {
contentfulStore(relativeUrl: { eq: $relativeUrl }) {
relativeUrl
shopPageTitle
mainPageTextContent {
childMarkdownRemark {
html
}
}
}
}
If you haven't learned how to use GraphiQL yet, try opening it at localhost:8000/___graphql! It's your best friend for learning how to query your Contentful schema.
I just started using apollo client on a React application and I'm stuck on caching.
I have a home page with a list of products where I do a query to get the id and name of those products and a product page where I do query for the ID, name, description and image.
I would like that if a user visits the home page fist then a specific product page to only do a query for that product's description and image, also display the name during the loading (since I should have cached it already).
I followed "Controlling the Store" part of the documentation (http://dev.apollodata.com/react/cache-updates.html) but still couldn't resolve it.
The query that is done when we go to the product page still asks for both the product's id and name whereas they should be cached since I already asked for them.
I think I'm missing something but I can't figure it out.
Here is a bit of the code:
// Create the apollo graphql client.
const apolloClient = new ApolloClient({
networkInterface: createNetworkInterface({
uri: `${process.env.GRAPHQL_ENDPOINT}`
}),
queryTransformer: addTypename,
dataIdFromObject: (result) => {
if (result.id && result.__typename) {
console.log(result.id, result.__typename); //can see this on console, seems okey
return result.__typename + result.id;
}
// Make sure to return null if this object doesn't have an ID
return null;
},
});
// home page query
// return an array of objects (Product)
export default graphql(gql`
query ProductsQuery {
products {
id, name
}
}
`)(Home);
//product page query
//return an object (Product)
export default graphql(gql`
query ProductQuery($productId: ID!) {
product(id: $productId) {
id, name, description, image
}
}
`,{
options: props => ({ variables: { productId: props.params.id } }),
props: ({ data: { loading, product } }) => ({
loading,
product,})
})(Product);
And my console output:
The answer to your question actually has two parts:
The client cannot actually tell for sure that these queries resolve to the same object in the cache, because they have a different path. One starts with products, the other with product. There's an open PR for client-side resolvers, which will let you give the client hints about where to find things in the cache, even if you haven't explicitly queried for them. I expect that we will publish that feature within a week or two.
Even with client-side resolvers, Apollo Client won't do exactly what you described above, because Apollo Client no longer does query diffing since version 0.5. Instead, all queries are fully static now. That means even if your query is in the cache partially, the full query will be sent to the server. This has a number of advantages that are laid out in this blog post.
You will still be able to display the part that's in the cache first, by setting returnPartialData: true in the options.
This question is quite old, however, there is a solution to map the query to the correct location using cacheRedirects
In my project, I have a projects query and a project query.
I can make a cacheRedirect like below:
const client = new ApolloClient({
uri: "http://localhost:3000/graphql",
request: async (operation) => {
const token = await localStorage.getItem('authToken');
operation.setContext({
headers: {
authorization: token
}
});
},
cacheRedirects: {
Query: {
project: (_, { id }, { getCacheKey }) => getCacheKey({ id, __typename: 'Project' })
}
}
});
Then when I load my dashboard, there is 1 query which gets projects. And then when navigating to a single project. No network request is made because it's reading from the cache 🎉
Read the full documentation on Cache Redirects