I will like to implement a follow and unfollow system that's base on objects IDS in the state. Like for example if a user.id is already in the arrays of users IDS in the state show unfollow button else show follow button. All being implemented on a single user component follow button not affecting the rest of the user's follow or unfollow button.
Here's my code for a better understanding of the question:
Thanks in advance for your help, which I will really appreciate.
import React, { useState } from 'react'
import { Pressable, Text, View } from 'react-native'
const users = [
{
id: 1,
user_id: 1,
username: 'Jerry'
},
{
id: 2,
user_id: 2,
username: 'Peter'
},
{
id: 3,
user_id: 3,
username: 'Sumo'
},
{
id: 4,
user_id: 4,
username: 'Musu'
}]
export default function TestingScreen() {
let initialState = [
{
id: 1,
user_id: 1,
username: 'Jerry'
}
]
const [followingList, setFollowingList] = useState(initialState);
const ids = followingList.map((following) => following.id);
alert(JSON.stringify(followingList));
return (
<View style={{
backgroundColor: 'white',
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}}>
{users.map((user, index) => (
<View key={index}>
<Text style={{fontSize: 20}}>{user.id}</Text>
<Text style={{fontSize: 20}}>{user.username}</Text>
{user.user_id !== ids ?
<Pressable
style={{
fontSize: 20,
backgroundColor: 'black',
padding: 10
}}
onPress={()=> setFollowingList(current => [...current, {id: user.id, username: user.username}])}>
<Text style={{fontSize: 20, color: 'white'}}>Follow</Text>
</Pressable>
:
<Pressable
onPress={() =>
setFollowingList((current) =>
current.filter((followingList) => followingList.id !== user.id))
}>
<Text style={{fontSize: 20}}>Unfollow</Text>
</Pressable>
}
</View>
))}
</View>
)
}
CodePudding user response:
use the includes
{!ids.includes(user.user_id) ? ...
Also, wrap this with useMemo
const ids = useMemo(() => followingList.map((following) => following.id), [followingList])