🎤 Builder Talk: The Story Behind Lady Gaga’s Digital Experience – Register now

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?

Related answers

Get more help in the community Slack

TopicCategoriesFeaturedRepliesLast Updated
Deploying Next JS on VercelJan 20, 2021
DOMParser is not defined at defaultParseHtmlDec 3, 2020
Error in Next.js tutorial with event handlers in server components.Feb 28, 2024
Discussion about the root layout for a website and how to properly implement it using Next.js.Apr 4, 2024
Hi all! Does anyone have problem on deoplloying on Vercel (Using Next. js as a frontend)? I have two test projects, andonce...Jan 25, 2021
How to Disallow Robots on a SubdomainNov 12, 2020
Troubleshooting reference fields in a Next.js Landing page templateMay 2, 2020
Restoring accidentally deleted documents in Sanity dataset without exporting.Jun 25, 2020
Help with Preview Mode and Next.js, issue with previewing draft changes from already published docSep 3, 2020
Discussion on using ISR and revalidation in Next.js to update content changes in Sanity StudioJan 7, 2021

Related contributions

Turbo Start Sanity
- Template

The battle-tested Sanity template that powers Roboto Studio's websites

Go to Turbo Start Sanity

Schema UI - Next.js Sanity Starter
- Template

A Next.js starter template with Next.js 15, Tailwind CSS, shadcn/ui, and Sanity CMS with Live Editing. Get production-ready React components with matching Sanity schemas and queries. Build dynamic pages faster while keeping full control over customization.

Serge Ovcharenko
Go to Schema UI - Next.js Sanity Starter

The Swaddle
- Made with Sanity

A new brand identity to represent a more mature company, to signify The Swaddle’s evolution from publisher to production house, combined with an easier to navigate platform that can surface multiple content types - drawing readers through The Swaddle’s content offering.

Nightjar
Go to The Swaddle