See Sanity in action 👀 Join us for a live product demo + Q&A →

Updating powerMeter in database using Patch request in Sanity.io

41 replies
Last updated: Feb 16, 2023
Is the following code correct for Patch request, updating data in database:

const updatePowerMeter = useCallback(async (personId) => {

try {

console.log('Updating power meter...');

const data = {

id: personId,

patch: {

inc: {

powerMeter: 1,

},

},

};

await client

.patch(data.id)

.set(data.patch)

.commit();

console.log('Power meter updated successfully');

} catch (error) {

console.error(error);

}

}, []);
Feb 15, 2023, 11:36 PM
You could probably shorten this to:
const updatePowerMeter = useCallback(async (personId) => {
    try {
      console.log('Updating power meter...');
      await client
        .patch(personId)
        .inc({ powerMeter: 1 })
        .commit();
      console.log('Power meter updated successfully');
    } catch (error) {
      console.error(error);
    }
  }, []);
Feb 16, 2023, 12:00 AM
But it's not updating the powermeter entry in database. What I could be doin wrong?
Feb 16, 2023, 12:01 AM
Your client may not be configured correctly. There may be a misspelling in your schema so that the
powerMeter
field doesn’t actually exist. Those would be two places to check first.
Feb 16, 2023, 12:03 AM
Can you share your client?
Feb 16, 2023, 12:04 AM
Ok let me check. Client is fine as data is getting fetched
Feb 16, 2023, 12:04 AM
Have you added a token?
Feb 16, 2023, 12:04 AM
Let me open laptop I just closed it in frustration
Feb 16, 2023, 12:04 AM
Yes I have added
Feb 16, 2023, 12:04 AM
Kindly give me 2 mins
Feb 16, 2023, 12:05 AM
Let me open laptop I just closed it in frustration
I have been there, my friend!
Feb 16, 2023, 12:05 AM
import sanityClient from '@sanity/client';

import imageUrlBuilder from '@sanity/image-url';


export const client = sanityClient({

projectId: process.env.REACT_APP_SANITY_PROJECT_ID,

dataset: 'production',

apiVersion: '2021-10-21',

useCdn: true,

token: process.env.REACT_APP_SANITY_TOKEN,

});


const builder = imageUrlBuilder(client);


export const urlFor = (source) => builder.image(source);
Feb 16, 2023, 12:06 AM
the client
Feb 16, 2023, 12:07 AM
dataset entry name is correct too
Feb 16, 2023, 12:08 AM
It may be that the token isn’t getting picked up from your env. Just to test it, can you try hardcoding it and running the patch?
Feb 16, 2023, 12:08 AM
ok let me check
Feb 16, 2023, 12:08 AM
No still no update
Feb 16, 2023, 12:09 AM
token is picked up
Feb 16, 2023, 12:10 AM
this token has editor permissions
Feb 16, 2023, 12:10 AM
The function runs when it’s supposed to, right? You get those logs in the console?
Feb 16, 2023, 12:11 AM
yes i get console.logs
Feb 16, 2023, 12:11 AM
I am updating powerMeter per visit on the page in react. But on doing refresh it isn't updating.
Feb 16, 2023, 12:12 AM
Would you like to see react component code?
Feb 16, 2023, 12:12 AM
Yes please!
Feb 16, 2023, 12:13 AM
ok wait
Feb 16, 2023, 12:13 AM
import React, { useState, useEffect, useCallback } from 'react';

import { client } from '../../../client';

import { useParams, Link } from 'react-router-dom';

import './Person.css';


export const Person = () => {

const { slug } = useParams();

const [person, setPerson] = useState(null);


const updatePowerMeter = useCallback(async (personId) => {

try {


const data = {

id: personId,

patch: {

inc: {

powerMeter: 1,

},

},

};

await client

.patch(data.id)

.set(data.patch)

.commit();

} catch (error) {

console.error(error);

}

}, []);

`const personQuery = `*[_type == "facesCelebs" && slug.current == '${slug}'][0]{name, _id, quotesbyPerson, profession, gender, ethnicity, powerMeter, slug, country, image {asset -> {url}}}`;`


useEffect(() => {

try {

client

.fetch(personQuery)

.then((data) => {

setPerson(data);

updatePowerMeter(data._id);

})

.catch((error) => console.log(error));

} catch (error) {}

}, [personQuery, updatePowerMeter]);


if (person === null) return <div><progress className="progress is-large is-info" max="100">60%</progress></div>;


const randomQuote = person.quotesbyPerson[Math.floor(Math.random() * person.quotesbyPerson.length)].quote;

return (

<>

<section className="hero is-bold heroColor">

<div className="hero-body" key={person.quotesbyPerson._key}>

<div className="container">

<div className='columns is-align-items-center is-flex-direction-column'>

<div className='column '>

<h1 className="titlePerson">{person.name}</h1>

</div>

<div className='column'>

<h2 className="subtitlePerson">"{randomQuote}" {person.powerMeter}</h2>

</div>

</div>

</div>


</div>

</section>

<div className="container">

<div className="columns">

<div className="column">

<figure>

<img className="is-rounded" src={person.image.asset.url} alt={person.name}  />

</figure>

</div>

<div>


</div>

</div>

</div>

</>

)

}


export default Person;
Feb 16, 2023, 12:13 AM
Hi, there?
Feb 16, 2023, 12:16 AM
Got it, just looking through it now.
Feb 16, 2023, 12:16 AM
ok
Feb 16, 2023, 12:16 AM
Can you try logging the
personId
to make sure the function is getting an id?
Feb 16, 2023, 12:19 AM
ok wait plz
Feb 16, 2023, 12:19 AM
Yup fetching correct id
Feb 16, 2023, 12:20 AM
It looks like your component still has the original patch you posted. Did you try the shortened version I shared?
Feb 16, 2023, 12:21 AM
let me try that
Feb 16, 2023, 12:21 AM
Worked
Feb 16, 2023, 12:22 AM
Oh good!
Feb 16, 2023, 12:23 AM
Let me try on live website
Feb 16, 2023, 12:23 AM
working great - but if any person don't have powerMeter value it shows client error in console
Feb 16, 2023, 12:24 AM
rest everything is fine
Feb 16, 2023, 12:24 AM
If you add this before the patch it should fix that. So it should look like this:
const updatePowerMeter = useCallback(async (personId) => {
    try {
      console.log('Updating power meter...');
      await client
        .patch(personId)
        .setIfMissing({ powerMeter: 0 })
        .inc({ powerMeter: 1 })
        .commit();
      console.log('Power meter updated successfully');
    } catch (error) {
      console.error(error);
    }
  }, []);
Feb 16, 2023, 12:27 AM
Worked - thanks a lot
Feb 16, 2023, 12:29 AM
You’re welcome!
Feb 16, 2023, 12:29 AM

Sanity.io – build remarkable experiences at scale

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