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
}
`