Issue with Gatsby watch mode not refreshing when referenced document is updated in Sanity CMS.

71 replies
Last updated: May 21, 2021
Watch Mode does not refresh when a referenced document is updated in the CMS. Is this the expected behavior?
Stack is, React, Gatsby 3.x

This is schema from my ‘page’ document.

{
      name: "content",
      type: "array",
      title: "Page Sections",
      description: "Add, edit, and reorder sections",      
      of: [        
        {
          type: 'reference',
          to: [            
            { type: 'nav' },
            { type: 'section' },
            { type: 'footer' }
          ]
        }
      ],
    },
nav, section, and footer are all type ‘document’. for example…


export default {
  type: 'document',
  name: 'section',
  title: 'Page Sections',
  fields: [   
    {
      name: 'meta',
      title: 'Section Meta Data',
      type: 'meta'
    },
...
Gatsby Config is set properly


{
      resolve: `gatsby-source-sanity`,
      options: {
        projectId: `asdfasdf`,
        dataset: `template`,
        watchMode: true,
        overlayDrafts: true,        
        token: process.env.MY_SANITY_TOKEN,        
      },
    },
In the CMS / Studio, when you edit one of the fields, you can see Gatsby re-compile in dev mode from the terminal, however, the page does not auto reload. If I click the reload button or do a hard refresh in the browser, the changes do not render.

The only way to get it to render the changes is to go back to the CMS and edit a field on the main “Page” document. Then it refreshes immediately.

Any insight, even if it’s “Hey, this is the expected behavior” would be helpful.
AI Update

Based on the Sanity documentation I've reviewed, I cannot definitively confirm whether the behavior you're experiencing is expected or a bug. The gatsby-source-sanity documentation describes that watchMode enables real-time content preview by setting up a listener that pushes changes from Sanity to Gatsby, but it doesn't explicitly address how referenced documents should behave in this scenario.

What we know about gatsby-source-sanity:

The plugin is designed to be highly efficient, making only two API requests during the build process. When watchMode is enabled, it sets up a listener for real-time updates. However, the official documentation doesn't clarify whether changes to referenced documents should automatically trigger rebuilds of pages that reference them.

Your specific situation:

You're seeing Gatsby recompile when you edit a referenced document (visible in terminal), but the page doesn't reload with the changes until you edit the parent page document. This suggests the plugin is detecting the change but may not be triggering the full rebuild chain for documents that reference the changed content.

Potential approaches to investigate:

  1. Check your GraphQL queries: Make sure you're using _rawContent fields with resolveReferences when querying referenced documents:
query {
  sanityPage {
    _rawContent(resolveReferences: {maxDepth: 5})
  }
}

The _raw fields are specific to gatsby-source-sanity and designed to properly resolve references within your content.

  1. Verify your token permissions: Ensure your MY_SANITY_TOKEN has read permissions for all the document types (page, nav, section, footer).

  2. Check the gatsby-source-sanity GitHub issues: This might be a known issue or limitation with the plugin. I'd recommend searching the gatsby-source-sanity GitHub repository for similar issues or opening a new issue with your specific setup to get input from the maintainers.

  3. Temporary workaround: As you've discovered, editing the parent document triggers the refresh. You could add a "Last Modified" timestamp field to your page document and update it when needed during development.

Without access to verified information about this specific behavior in the plugin's issue tracker or detailed documentation, I can't confirm if this is expected behavior or a bug. I'd recommend reaching out to the Sanity community on their Slack community or opening a GitHub issue with this specific scenario to get a definitive answer from the plugin maintainers who can confirm the intended behavior.

user M
Does that emoji mean you want me to create a ticket in github for this?
Great thanks. I’m also looking at the approach in the “Kitchen Sink” repo. I noticed that a reference object is used between the ‘author’ document and the ‘post’ document.
For example: ‘post’ document includes an array of ‘authorReference’ objects that point to an ‘author’ document.

I tried that pattern and still, no joy. However, is there a reason for using a reference object rather than just making the reference directly?
Great thanks. I’m also looking at the approach in the “Kitchen Sink” repo. I noticed that a reference object is used between the ‘author’ document and the ‘post’ document.
For example: ‘post’ document includes an array of ‘authorReference’ objects that point to an ‘author’ document.

I tried that pattern and still, no joy. However, is there a reason for using a reference object rather than just making the reference directly?
Hmm, remind me, are there more fields in the
authorReference
object than just the reference?
Hmm, remind me, are there more fields in the
authorReference
object than just the reference?
_export_ default {

name: 'authorReference',

type: 'object',

title: 'Author reference',

fields: [

{

name: 'author',

type: 'reference',

to: [

{

type: 'author'

}

]

}

],

preview: {

select: {

title: 'author.name',

media: 'author.image.asset'

}

}

}
I’m not sure on this one. I’ll take a look a the repo and see if I can figure it out.
The Post document also references another document directly.
{

name: 'categories',

type: 'array',

title: 'Categories',

of: [

{

type: 'reference',

to: {

type: 'category',

},

},

],

},
I’m just hoping that I’m missing something silly here. But so far… I’m stumped.
Ah, it might be so that it can create the custom preview.
This watch mode issue is my biggest blocker at the moment. So I’m on it until I figure it out. I don’t want to go too far until I have this sorted. Thanks for the help 🙂
I’ll let you know as soon as I have more info on the watch mode issue!
I've seen this before also, I think you are correct
user M
that it does not work correctly when nested docs are modified. Maybe file an issue in the sanity github?
user M
I’m looking for any workaround I can find on this now as well. I’m even thinking about trying to materialize a data change on a field of the main document just to trigger the reload. But that feels like a dirty hack 🙂
check out the sanity source code and see what is going on in watch mode it's open source!
I think this is happening in the gatsby-source-sanity plugin. That’s where I’m looking now.
Somewhere in here…
if (watchMode) {
send links to gh code
I was wondering that and… it could also be something in the Sanity Client itself. Line 289 calls ‘client’ which is the sanity client instantiated by the getClient function. So it could get pretty deep for a Sanity Nubie like me.
Hoping to find a solution soon though, one of the big wins with Sanity over others like contentful is the watchmode edititing. Not the only thing, but it’s pretty big.
user M
user M
added a ticket this morning. Feel free to add anything I missed:

https://github.com/sanity-io/gatsby-source-sanity/issues/123
user C
I thought I was either missing something or eating crazy pills! Thanks for filing this. I’m going to add that same boolean to my main page document as well. I wonder if there’s a way to have related documents toggle the boolean for us.
You are welcome! Let me know if you come up with something!🙌
user C
user M
Do you think this could be caused by using static queries in serializer components? I’m wondering if querying for all data at the page level and prop drilling it would fix this. It would be unfortunate if that’s the case, but I’m going to try it.
user M
user C
user M
I’ve added some additional observations to the ticket in GitHub. Hopefully this helps. I’m at a blocker with this at the moment 🙂
user C
user M
I made some progress on this. I’ll give you a more detailed response shortly, but….
user C
user M
I made some progress on this. I’ll give you a more detailed response shortly, but….
It appears that using the _rawQuery is the source of the problem.
example
export const PageQuery = graphql`
  fragment PageInfo on SanityPage {
    _id
    _key
    _updatedAt
    _rawContent(resolveReferences: {maxDepth: 10})
    content {
      ... on SanitySection {
        _rawContent(resolveReferences: {maxDepth: 10})
        _rawImage
      }
    }
  }
`
the _rawContent attribute query will not trigger a data update and therefore will not re-render the page.
However, the explicit query content { … on SanitySection { _rawContent …

That will trigger the update to the data and will trigger the re-render.
the _rawContent attribute query will not trigger a data update and therefore will not re-render the page.
However, the explicit query content { … on SanitySection { _rawContent …

That will trigger the update to the data and will trigger the re-render.
I don’t know if this is a feature or a bug 🙂
I’ve dealt with that before.
It might be because _rawContent is already defined two levels up.
_rawContent(resolveReferences: 

_rawContent within _rawContent is redundant.
(I just had this explained to me a few weeks ago by someone.)
Like it might be de-duping even though it’s a child node?
I could try changing the schema for the section data and see if giving it a different name makes a difference.
I could try changing the schema for the section data and see if giving it a different name makes a difference.
I think not using _raw twice is all you have to do
This is the page schema…{

name: "content",

type: "array",

title: "Page Sections",

description: "Add, edit, and reorder sections",

of: [

{

type: "reference",

to: [

{ type: "nav" },

{ type: 'section' },

],

},

],

},
Section Schema also has a “content” attribute that will become _rawContent in the GraphQL query.
From the Section Schema

{

name: "content",

type: "simpleBlockContent",

title: "Section Content",

description: "Section Content defaults to Typography Body1",

},
I’ll change this and see if it works.
if _raw is used in the GraphQL anything after that doesn’t need to be _raw (I may be mistaken)
So you should’nt have to change the schema, just take _raw out of the second _rawContent
I’m going to give it a quick go. one moment.
While you do that, I’ll be more clear about this, one moment…
`_export_ const PageQuery = graphql``
fragment PageInfo on SanityPage {

_id

_key

_updatedAt


// This is the _raw query that gatsty-source-sanity gives you as a

// convenient way to access all content

_rawContent(resolveReferences: {maxDepth: 10})


// this is me explicitly creating a query for the page sections

content {

... on SanitySection {

// this is the _rawContent convenience query for the section schema

_rawContent(resolveReferences: {maxDepth: 10})

_rawImage

}

}

}
```
While you do that, I’ll be more clear about this, one moment…
I was thinking you’d use this instead of that:
`_export_ const PageQuery = graphql``
fragment PageInfo on SanityPage {

_id

_key

_updatedAt


// This is the _raw query

_rawContent(resolveReferences: {maxDepth: 10})

*content* {

... on SanitySection {

content(resolveReferences: {maxDepth: 10})

image

}

}

}
```
(It’ll be a bit on my end. Got something coming up soon that’ll take 45min-1hr)
What I noticed is that if you use the top level _rawContent query, watch mode will only trigger a re-query of the data and update to the data for the top level parent argument. It won’t watch any referenced documents and trigger a re-query and update to the data.
(It’ll be a bit on my end. Got something coming up soon that’ll take 45min-1hr)
However, when you explicitly query the referenced document, then it will trigger the re-query. For clarity… this is the query that triggers the update to the data

*content* {

... on SanitySection {

content(resolveReferences: {maxDepth: 10})

image

}
Hi User,

user V
and I were looking through this last night.
He came up with a good workaround. I tested it this morning with my pages and they now update when the content is changed.
If you add a simple query to the page template you are using (or page you have your GraphQL) it’ll get noticed when the content is changed.
Ex:


allSanityProduct {

edges {

node {

id

}

}

}

I’ve got this added to my page.js template and I’m not using it for anything in the content. Just having it in the Query causes those documents to be watched.
user C
I was thinking the same thing last night… then I got tired and needed a beer 🙂 I’ll give this a try.
user C
user M
I got this to work, but I think that someone should really detail this out. It’s not clear from the documentation that you need to make an explicit query outside of the _raw query in order force the data reload. It’s reasonable to assume that the _raw query would be sufficient.
user M
mind adding more info to the issue
user C
filed? I'm not clear on how this even works, why would a top level document that isn't changed or used cause it to watch page level items that are changed?
user M
mind adding more info to the issue
user C
filed? I'm not clear on how this even works, why would a top level document that isn't changed or used cause it to watch page level items that are changed?
user M
I’ll send you a video I filmed. Not sure if that will assist w/ what User is working through but it will show you the scenario I encountered.
Feel free to add to the issue also the more evidence the better 👍
Looks like User updated the issue makes sense now thanks!
Looks like User updated the issue makes sense now thanks!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?