How to connect follow button to Sanity dataset and save user data?

7 replies
Last updated: Nov 29, 2025
Hey guys!I want to have a "FOLLOW" option in my sicial media project and this is my frontend code and sanity file.
but I don't know haw to connect them to each other and when the user click on the "Follow" button the data of the user send to the sanity dataset
can someone twell me what shpuld I do?

 <style>{`
       .container { 
        text-align: center;}

        .blackButton{
         font-weight: bold; 
         content: "Following";         
          position: relative;
          width: 100px;
          height: 40px;
          margin-left: auto;
          margin-right: auto;
          margin-top: 20px;
          color: white;
          background-color: rgb(255, 0, 0);
                   
          text-align: center;
          border-radius: 25px;
        }
        
        .whiteButton{
          content: "Follow";
          font-weight: bold;
          width: 100px;
          height: 40px;
          margin-left: auto;
          margin-right: auto;
          background-color: rgb(179, 179, 179);
          color: rgb(255, 255, 255);
          text-align: center;
          border-radius: 25px;
          margin-top: 20px;
          
        }
      `}</style>
      <button
        className={buttons}
        onClick={(e) => setbutton((buttons) => (buttons === "blackButton" ? "whiteButton" : "blackButton"),
        addFollower(buttons),
        
        )
      }
      >
      Following    
      </button>

export default{
    name: 'user',
    title: 'User',
    type: 'document',
    fields: [
        {
            name: 'userName',
            title: 'UserName',
            type: 'string' 
        },
        {
            name: 'image',
            title: 'Image',
            type: 'string'
        },
        {
            name: 'detail',
            title: 'Detail',
            type: 'string'
        },
        {
            name: 'following',
            title: 'Following',
            type: 'reference',
            to: [{ type:'user' }],
        },
    ]
}
AI Update

I can help you connect your frontend follow button to Sanity! You'll need to use the Sanity client to update the user document when someone clicks the follow button. Here's what you need to do:

Install and Configure the Sanity Client

First, install the Sanity client in your frontend project:

npm install @sanity/client

Then create a client instance:

import {createClient} from '@sanity/client'

const client = createClient({
  projectId: 'your-project-id',
  dataset: 'your-dataset-name',
  useCdn: false, // set to false for mutations
  apiVersion: '2024-01-01', // use current date
  token: 'your-write-token' // get this from manage.sanity.io
})

Important: You'll need a write token from your Sanity project. Go to manage.sanity.io → your project → API → Tokens and create a token with write permissions.

Fix Your Schema

Your current schema has an issue - following should be an array of references, not a single reference:

export default {
  name: 'user',
  title: 'User',
  type: 'document',
  fields: [
    {
      name: 'userName',
      title: 'UserName',
      type: 'string' 
    },
    {
      name: 'image',
      title: 'Image',
      type: 'string'
    },
    {
      name: 'detail',
      title: 'Detail',
      type: 'string'
    },
    {
      name: 'following',
      title: 'Following',
      type: 'array',
      of: [{type: 'reference', to: [{type: 'user'}]}]
    },
  ]
}

Update Your Frontend Code

Here's how to implement the follow functionality:

const [isFollowing, setIsFollowing] = useState(false);

const handleFollow = async () => {
  const currentUserId = 'current-user-id'; // ID of logged-in user
  const targetUserId = 'target-user-id'; // ID of user being followed
  
  try {
    if (isFollowing) {
      // Unfollow - remove from array
      await client
        .patch(currentUserId)
        .unset([`following[_ref=="${targetUserId}"]`])
        .commit();
    } else {
      // Follow - add to array
      await client
        .patch(currentUserId)
        .setIfMissing({following: []})
        .append('following', [{_type: 'reference', _ref: targetUserId}])
        .commit();
    }
    
    setIsFollowing(!isFollowing);
  } catch (error) {
    console.error('Follow error:', error);
  }
};

return (
  <button
    className={isFollowing ? "blackButton" : "whiteButton"}
    onClick={handleFollow}
  >
    {isFollowing ? 'Following' : 'Follow'}
  </button>
);

Key Points

  1. Use patch() for updates: The Mutation API provides patch operations to modify existing documents without replacing them entirely

  2. Array operations: Use append() to add references and unset() with array syntax to remove specific references. The path following[_ref=="${targetUserId}"] targets the specific reference in the array.

  3. Security: Never expose your write token in frontend code! For production, you should:

    • Create a serverless function or API route that handles the mutation
    • Pass the user IDs to that endpoint
    • Keep the token server-side only
  4. Alternative approach: You could also use Sanity Functions (serverless compute within Sanity) to handle this logic securely without managing your own backend

The setIfMissing() ensures the following array exists before appending to it, preventing errors if this is the user's first follow. Check out the JavaScript client documentation for more details on all available operations!

Show original thread
7 replies

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?