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

How to return updated values from a patch event in Sanity

5 replies
Last updated: Apr 29, 2022
Hello everyone , Could anyone help me out by showing me a way to return updated values from a patch event. I tried in below way but it does not return values in then ( ) function .What I found that patch returns id maximum and we can query the document using that id to fetch values , these are previous values not updated one. Could anyone just point me what goes wrong here....I just want to fetch updated comments after patch event took place. I confirmed update values in sanity studio. Or Give me a general idea , how to return updated values from a patch event. `axios.post (...patch mutation runs here).then((response,data)=>{ console.log(response.data.results[0].id); client.fetch(
*[_type == "blog" && _id == $id][0]
, {`
id: response.data.results[0].id,

})                                                                                                                                                                                                                                                                             .then((x)=>{

console.log(x.comments)

return  res.status(201).send({

message: 'CommentUpdated',

comments: x.comments

})

})

.catch(function (error) {

console.log(error.message);

});                                                                                                                                                                                                                                                                       }).catch(function (error) {

console.log(error.message);

});
Apr 20, 2022, 8:51 AM
Thank you so much Racheal.It's now very much clear.
Apr 21, 2022, 4:11 AM
Hello Racheal , could you please tell me where this queue comes from in above code.I mean queue is not defined.
Apr 28, 2022, 10:05 AM
Sure, it's an external package for limiting the rate at which you write to Sanity.
import cq from 'concurrent-queue';

let queue = cq()
  .limit({ concurrency: 25 })
  .process(function (task) {
    return new Promise(function (resolve, reject) {
      setTimeout(resolve.bind(undefined, task), 1000);
    });
  });
Apr 28, 2022, 2:17 PM
Hello Racheal, Thanks for your reply. I am getting error message " oh no update failed : the mutation(s) failed, Insufficient permission "update" required." Do we require to pass token in http header? I have executed the method using mutation after passing token in headers , it throws above error if below function triggered.
handler.use(auth).post(async(req,res)=>{

//method for new comments

//from concurrent-queue package for limiting the rate

let queue = cq()

.limit({ concurrency: 25 })

.process(function (task) {

return new Promise(function (resolve, reject) {

setTimeout(resolve.bind(undefined, task), 1000);

});

});

`const query = `*[_type == 'blog']`;`

const docs = await client.fetch(query);



// Loop through all of the docs returned from our query


for (const doc of docs) {

queue(doc).then(async () => {

// Add a message to help us know the post is happening
`console.log(
Mutating ${doc._id}
);`
// Tell the client to patch the current document

client

.patch(doc._id)

// Set the field

.setIfMissing({ comments: [] })

.insert('after', 'comments[-1]', [

{

name: req.user.name,

rating: Number(req.body.rating),

comment: req.body.comment,

user: {

_type: 'reference',

_ref: req.user._id,

}}

])

.set({

commentsTotalNumber: blog && blog.comments && blog.comments.length,

rating: blog && blog.comments && blog.comments.reduce((a, c) => c.rating + a, 0) / blog.comments.length,

})


// Commit the changes


.commit()

.then((updatedDoc) =>{
`console.log(
Comment is updated! New document:
, updatedDoc)`
res.status(201).send({

message: 'Comment is Posted',

comments: updatedDoc

})


}


)

.catch((err) =>

console.error('Oh no, the update failed: ', err.message)

);



});

}


});
Apr 29, 2022, 5:09 AM
Are you running this script from your root folder using
sanity exec
? If so, you can use the flag --withUserToken to pass in your token.
Apr 29, 2022, 2:45 PM

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?