Discussion on how to add a "Follow" option in a social media project and how to connect frontend code and sanity file.

7 replies
Last updated: Aug 18, 2022
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!

Hi!I know that it's unrelated, but I'm genuinely curious about your usage of the CSS content property. Is it supposed to change the button text upon clicking it?
user E
Hi!yes it's supposed to change the buttton color and text when we cliking it.but hunestly the text doesn;t change
😞
You'd need to submit a patch to your dataset that adds a reference to your
following
array. You can read about adding items to an array here .
user M
Thank you!But does it shows the posts of followed person in my home page too?How should I set that?
On your homepage, you'd need to query for all of the posts the followed person has created. Since your user already has already referenced the other user it's a pretty easy GROQ query. I don't know what your schema looks like, but if the followed user is listed as the
author
on a post, it would look something like this:
{
//...the rest of your query
  'followedPosts': *[_type == 'post' && author._ref in ^.following[]._ref ]
}
That's just an example, though. You would need to tweak it to work for your content model.
user M
AhaaI think I got it Thank you so much.
Can I ask more questions if I get some problems? :)
Sure! Maybe open a new thread in the channel though! 🙂

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?