🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Subscribe to a Document and Re-Render with React When Updated

3 replies
Last updated: Jul 26, 2022
I wanna make a subscription to a document, and I wanna to react re-render if are any update... How I can do that?
Jul 26, 2022, 1:51 AM
https://www.sanity.io/docs/realtime-updates
is probably a good place to start.

In the example the fetch ends in a console log but it probably makes the most sense for whatever you're rerendering to include the current state of a destructured useState hook and set it inside the same spot the console log is happening.
Jul 26, 2022, 2:04 AM
I read that, but like, I need to update the component right?
Jul 26, 2022, 2:08 AM
When the update hits, you setting the new state triggers the component update, so long as the component contains a reference to the current state.
So if you did


const [ authorName, setAuthorName ] = useState('')
at the start of the component and separately, had a listener going like this (

const subscription = client.listen(query, params)
  .subscribe(update => {
    const comment = update.result
    setAuthorName(comment.author)
  })
and in the JSX returned did something like

<h1>{authorName}</h1>
it should update as the new name got set.

That was just my thought on the pattern. It seems to be corroborated by this repo:
https://github.com/sanity-io/syncing-example/blob/main/src/List.jsx but full disclosure I haven't built anything with the listen endpoint yet.
Jul 26, 2022, 2:36 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?