Discussion on how to add a "Follow" option in a social media project and how to connect frontend code and sanity file.
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/clientThen 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
Use
patch()for updates: The Mutation API provides patch operations to modify existing documents without replacing them entirelyArray operations: Use
append()to add references andunset()with array syntax to remove specific references. The pathfollowing[_ref=="${targetUserId}"]targets the specific reference in the array.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
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!
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.