Help needed with updating likesCount in a dataset using Sanity.io and Next.js

7 replies
Last updated: Feb 6, 2023
Hi guys, I am a newbie to the headless CMS world navigating through sanity.io . I need help updating the likesCount in my dataset when user clicks on the like button.

I was able to use sanity to manually import some data into my sanity dataset and fetch it from an endpoint that I created in my nextjs App. now I need your help to mutate a number property.
this is a sample of one of my documents


likes:120
price:50
rating:4.5
seller:{…} 2 properties
_ref:3a45f32e-e6b3-4eef-984a-515a595b25ad
_type:reference
serviceImageUrl:<https://cdn.discordapp.com/attachments/990816819654852648/1063634376849629194/needmadnes33_two_people_sitting_on_the_couch_and_watching_tv_tv_1ff1b756-feb1-410a-97a3-97055562b522.png>
title:Accompaniment for a TV show marathon
visits:180
Now I have a button in my react component,

<button onClick={addToLikes}>Likes: {selectedService?.likes}</button>
My addToLikes function is as follows:


const addToLikes = async (selectedService) => {
  console.log("addToLikes triggered");
  try {
    const data = { id: selectedService.id };
    const result = await axios.patch("/api/updateLikes", data);
    console.log(result.data);
  } catch (error) {
    console.error(error);
  }
};
I want to make the addLikes function change the value of my dataSet in sanity. so when the user click the button, it should increase the likes by 1. But I am having issues with this. This is how I have my API endpoint set up for mutation, but it is giving me server error

/pages/api/updateLikes.js file below:

import axios from "axios";

export default async function handler(request, response) {
  try {
    const data = JSON.parse(request.body);

    const mutations = {
      mutations: [
        {
          patch: {
            _id: data.id,
            inc: { likes: 1 },
          },
        },
      ],
    };

    const apiEndpoint = `https://${process.env.NEXT_PUBLIC_SANITY_PROJECT_ID}.<http://api.sanity.io/v2023-02-05/data/mutate/${process.env.NEXT_PUBLIC_SANITY_DATASET}`;|api.sanity.io/v2023-02-05/data/mutate/${process.env.NEXT_PUBLIC_SANITY_DATASET}`;>
    const result = await axios.patch(apiEndpoint, mutations, {
      headers: {
        "content-type": "application/json;charset=utf-8",
        Authorization: `Bearer ${process.env.SANITY_API_TOKEN}`,
      },
      method: "PATCH",
    });
    await result.data;
    response.status(200).json({ message: "likes increased" });
  } catch (error) {
    console.error(error);
    response.status(500).json({ message: "Server error" });
  }
}
What am I doing wrong here?
Feb 6, 2023, 2:13 AM
user T
do you think you could help me out with this a little?
Feb 6, 2023, 2:38 PM
Hey User, I’d probably start with using Sanity Client to perform the patch, it should greatly simplify your code!

https://github.com/sanity-io/client#patchupdate-a-document
Feb 6, 2023, 3:07 PM
Thank you , let me look into this.
Feb 6, 2023, 3:25 PM
does this work well with nextjs projects as well?
Feb 6, 2023, 3:26 PM
Sure does!
Feb 6, 2023, 3:30 PM
Perhaps take a look at next-sanity also to register your client globally in your app
https://github.com/sanity-io/next-sanity
Feb 6, 2023, 3:30 PM
And please make sure to use gender neutral language in the community 🙂
Feb 6, 2023, 8:10 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?