Updating powerMeter in database using Patch request in Sanity.io
41 replies
Last updated: Feb 16, 2023
P
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
R
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
P
But it's not updating the powermeter entry in database. What I could be doin wrong?
Feb 16, 2023, 12:01 AM
R
Your client may not be configured correctly. There may be a misspelling in your schema so that the
powerMeterfield doesn’t actually exist. Those would be two places to check first.
Feb 16, 2023, 12:03 AM
R
Can you share your client?
Feb 16, 2023, 12:04 AM
P
Ok let me check. Client is fine as data is getting fetched
Feb 16, 2023, 12:04 AM
R
Have you added a token?
Feb 16, 2023, 12:04 AM
P
Let me open laptop I just closed it in frustration
Feb 16, 2023, 12:04 AM
P
Yes I have added
Feb 16, 2023, 12:04 AM
P
Kindly give me 2 mins
Feb 16, 2023, 12:05 AM
R
Let me open laptop I just closed it in frustrationI have been there, my friend!
Feb 16, 2023, 12:05 AM
P
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
P
the client
Feb 16, 2023, 12:07 AM
P
dataset entry name is correct too
Feb 16, 2023, 12:08 AM
R
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
P
ok let me check
Feb 16, 2023, 12:08 AM
P
No still no update
Feb 16, 2023, 12:09 AM
P
token is picked up
Feb 16, 2023, 12:10 AM
P
this token has editor permissions
Feb 16, 2023, 12:10 AM
R
The function runs when it’s supposed to, right? You get those logs in the console?
Feb 16, 2023, 12:11 AM
P
yes i get console.logs
Feb 16, 2023, 12:11 AM
P
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
P
Would you like to see react component code?
Feb 16, 2023, 12:12 AM
R
Yes please!
Feb 16, 2023, 12:13 AM
P
ok wait
Feb 16, 2023, 12:13 AM
P
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
P
Hi, there?
Feb 16, 2023, 12:16 AM
R
Got it, just looking through it now.
Feb 16, 2023, 12:16 AM
P
ok
Feb 16, 2023, 12:16 AM
R
Can you try logging the
personIdto make sure the function is getting an id?
Feb 16, 2023, 12:19 AM
P
ok wait plz
Feb 16, 2023, 12:19 AM
P
Yup fetching correct id
Feb 16, 2023, 12:20 AM
R
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
P
let me try that
Feb 16, 2023, 12:21 AM
P
Worked
Feb 16, 2023, 12:22 AM
R
Oh good!
Feb 16, 2023, 12:23 AM
P
Let me try on live website
Feb 16, 2023, 12:23 AM
P
working great - but if any person don't have powerMeter value it shows client error in console
Feb 16, 2023, 12:24 AM
P
rest everything is fine
Feb 16, 2023, 12:24 AM
R
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
P
Worked - thanks a lot
Feb 16, 2023, 12:29 AM
R
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.