检查用户是否已经关注,然后将按钮文本更改为”取消关注”。

huangapple go评论99阅读模式
英文:

Check if a user is already following, then change button text to unfollow

问题

我已经成功让用户在React中关注和取消关注彼此,现在我面临的唯一障碍是相应地更改按钮。这是我的API的基本结构:

我有一个"followers"字段,其中包含一个关注我的用户数组,如何检查已登录用户是否在该数组中,然后更改他们的按钮为"取消关注",否则按钮将显示"关注"。

我从本地存储的JWT中获取已登录用户的user_id:

const token = localStorage.getItem('authTokens');
const decoded = jwtDecode(token);
const user_id = decoded.user_id;

这些是按钮:

<div onClick={follow} className="follow-btn color2-bg">
  关注 <i className="fas fa-user-plus" />
</div>
<div onClick={unfollow} className="follow-btn color2-bg bg-danger">
  取消关注 <i className="fas fa-user-minus text-white" />
</div>

这是我的useState的外观:

const [profile, setProfile] = useState({
    user: '',
    full_name: '',
    ...
    followers: '',
});

因此,如果我想要获取正在查看其个人资料的用户的full_name,我可以使用 profile.full_name

我将提供更多需要的信息或细节。

编辑:这是如何将值添加到本地存储的方式:

// 这将用户的关注者保存到本地存储
const response = await api.get(baseUrl + '/service-provider/' + profile_ID + '/')
localStorage.setItem("followers", JSON.stringify(response.data.followers))

如何在页面刷新后保留文本 (关注或取消关注)

英文:

I have finally made it so that users can follow and unfollow each other in react, now the only obstacle I am left with is changing the button accordingly. This is the basic structure of my API:

{
    &quot;id&quot;:4,
    &quot;user&quot;: {
        &quot;id&quot;: 4,
        &quot;username&quot;: &quot;sammy&quot;
    },
    &quot;full_name&quot;: &quot;Sam Iyke&quot;,
    &quot;bio&quot;: &quot;Software Enginner&quot;,
    &quot;image&quot;: &quot;http://127.0.0.1:8000/media/user_images/ins-gallery_5.jpg&quot;,
  
    &quot;followers&quot;: [
        {
            &quot;id&quot;: 1,
            &quot;username&quot;: &quot;destiny&quot;,
            &quot;email&quot;: &quot;desphixs@gmail.com&quot;
        },
        {
          &quot;id&quot;: 5,
          &quot;username&quot;: &quot;jenny&quot;,
          &quot;email&quot;: &quot;jenny@gmail.com&quot;
        }
    ],
    &quot;date&quot;: &quot;2023-02-16T00:41:46.147589Z&quot;
}

I have a followers field there, that have an array of users that are following me, how do i check if the logged in user is in the array, then change thier button to Unfollow, else the button would be Follow.

I am getting the logged in user_id from localstorage jwt

const token = localStorage.getItem(&#39;authTokens&#39;);
const decoded = jwtDecode(token);
const user_id = decoded.user_id;

These are the button

&lt;div onClick={follow} className=&quot;follow-btn color2-bg&quot;&gt;
  Follow &lt;i className=&quot;fas fa-user-plus&quot; /&gt;
&lt;/div&gt;
&lt;div onClick={unfollow} className=&quot;follow-btn color2-bg bg-danger&quot;&gt;
  Unfollow &lt;i className=&quot;fas fa-user-minus text-white&quot; /&gt;
&lt;/div&gt;

This is how my useState looks like

const [ profile, setProfile ] = useState({
    user: &#39;&#39;,
    full_name:&quot;&quot;,
    ...
    followers:&quot;&quot;,
});

So if I want to get the full_name of the user that we are viewing their profile, I do profile.full_name

I would provide any more information or detail needed.

Edit

This is how i add the values to the localstorage

 // this saves the user followers to the localstorage
const response = await api.get(baseUrl + &#39;/service-provider/&#39; + profile_ID + &#39;/&#39;)
localStorage.setItem(&quot;followers&quot;, JSON.stringify(response.data.followers))

function followToggle (){
 if(isFollowing){
    //remove follower
    const followers = JSON.parse(localStorage.getItem(&quot;followers&quot;))
    let remaining = followers.filter(user=&gt;user.id!==user_id);
    localStorage.setItem(&quot;remaining&quot; ,JSON.stringify(remaining))
    setIsFollowing(false)
}
else{
    //add follower
    const followers = JSON.parse(localStorage.getItem(&quot;followers&quot;))
    followers.push(user_id);
    localStorage.setItem(&quot;followers&quot; ,JSON.stringify(followers))
    setIsFollowing(true)
 }
}

How to make the Text (Follow or Unfollow) retained after page refreshes?

答案1

得分: 1

首先,你可以创建另一个 state 变量来知道用户是否正在关注他或不关注他,或者可以手动执行以下步骤:

let userIndex = profile.followers.findIndex(i => i.id === currentUserId);
const [isFollowing, setIsFollowing] = useState(userIndex > -1);

然后在你的代码中,根据 isFollowing 的值显示不同的按钮:

{!isFollowing ? <div onClick={followToggle} className="follow-btn color2-bg">
  关注 <i className="fas fa-user-plus" />
</div> : <div onClick={followToggle} className="follow-btn color2-bg bg-danger">
  取消关注 <i className="fas fa-user-minus text-white" />
</div>}

最后,你的 followToggle 函数可以如下所示:

function followToggle() {
  if (isFollowing) {
    // 取消关注
    let followers = // 从本地存储获取关注者数组
    let remaining = followers.filter(user => user.id !== currentUserId);
    // 将 remaining 保存到本地存储中
  } else {
    // 关注
    let followers = // 从本地存储获取关注者数组
    followers.push(currentUser);
    // 将 followers 保存到本地存储中
  }
}

请注意,上述代码中的注释部分需要根据你的具体应用程序逻辑来填充,以确保它们与你的应用程序的数据和本地存储操作一致。

英文:

first of all you can create another state to know the user is following him or not, or can do it manually

let userIndex= profile.followers.findIndex(i=&gt;i.id===currentUserId)
const [isFollowing,setIsFollowing]=useState(userIndex &gt; -1);

then in your code

{!isFollowing ? &lt;div onClick={followToggle} className=&quot;follow-btn color2-bg&quot;&gt;
  Follow &lt;i className=&quot;fas fa-user-plus&quot; /&gt;
&lt;/div&gt;
:&lt;div onClick={followToggle} className=&quot;follow-btn color2-bg bg-danger&quot;&gt;
  Unfollow &lt;i className=&quot;fas fa-user-minus text-white&quot; /&gt;
&lt;/div&gt;
}

then your function wil be like this

function followToggle (){
 if(isFollowing){
//remove follower
let followers = //from local storage it should be an array 
let remaining = followers.filter(user=&gt;user.id!==currentUserId);
//set remaining to local storage
}
else{
//add follower
let followers = //from local storage it should be an array 
 followers.push(currentUser);
//set followers to local storage
}
}

huangapple
  • 本文由 发表于 2023年2月24日 09:02:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定