Reputation: 71
I have a "film" category in my Sanity database which has an array of comments.
In my UI, I present a pic of the film with the comments listed below the film. I created a function to add comments to the film and then fetch the film with the comments.
As you can see, in my addCommentToFilm function, I commit a patch query to Sanity to add a comment to the film; the commit returns a promise. I console log the response from Sanity, and it has the updated comments array (including the comment I just added). I then call a function to fetch the film from Sanity, but the film's comments array does not always have the last comment added: Sometimes it does, and sometimes I have to call the function a few times until I receive the updated array with the comment most recently added.
Does anyone know why this happens and whether there is a way to receive the updated list of comments consistently?
`
const addCommentToFilm = (filmId) => {
client
.patch(filmId)
.setIfMissing({ comments: [] })
.insert('after', 'comments[-1]', [{
comment,
_key: uuidV4(),
postedBy: {
_type: 'postedBy',
_ref: user._id,
}
}])
.commit()
.then((res) => {
console.log(res); // I get the film with the comments, including the comment I just added
fetchFilms(filmId);
})
.catch((error) => {
console.log('Comment post error: ', error);
})
}
const fetchFilm = (filmId) => {
client
.fetch(`*[_type == "film" && _id == "${filmId}"]`)
.then((res) => console.log(res)) // I get the film with the comments, sometimes with and sometimes without the comment I just added
}
`
Upvotes: 2
Views: 1452
Reputation: 71
OK, received this information on the Sanity help thread on Slack:
This might be related to me setting 'useCdn: true' in my client.js file, as there is a slight delay between purging/revalidating.
Link to docs: https://www.sanity.io/docs/api-cdn#da702944cd86
Once I changed my setting to 'useCdn: false' the problem was solved, and now I am getting the updated data from the database in response to my query.
Great support from Sanity on Slack!
Upvotes: 3