Reputation: 1
So, in a tab, i'm displaying a list of Friends, when selecting one of the friends, the data should go to another list Participants.
It works fine until you try to add another friend to the Participants. It just rewrites the last friend with the one just selected.
//imports...
Const Create = () {
//code for Friends list
let listParticipants = [];
let seeParticipants = [];
let [showParticipants, setShowParticipants] = useState([]);
const addParticipant = (participant) => {
if (alreadyParticipant(participant)) return console.log("Participant already");
seeParticipants.push(participant.accountId2);
listParticipants.push(
<TouchableOpacity>
<FriendCardAvatar key={key++} friend={participant} />
</TouchableOpacity>
);
setShowParticipants(listParticipants);
}
}
return (
<View>
//code
{showFriends}
</View>
<View>
//code
{showParticipants}
</View>
)
For some reason the whole code before addParticipant() is called whenever it's called.
This is my first react native project, hope to find a way around the problem.
Upvotes: 0
Views: 26
Reputation: 127
First of all you should not save the Element in the React State, like we use variables in Javascript or Jquery
It can be done with only one STATE instead of using all these
listParticipants = [];
let seeParticipants = [];
let [showParticipants, setShowParticipants] = useState([]);
I will give you an example hope it will help you understand
//imports...
Const Create = () {
//code for Friends list
let [showParticipants, setShowParticipants] = useState([]);
const addParticipant = (participant) => {
let alreadyParticipant = showParticipants.find((v,i)=>v.accountId2==participant.accountId2)
if (alreadyParticipant) return console.log("Participant already");
setShowParticipants(participant);
}
}
return (
<View>
//code
{showFriends}
</View>
<View>
{showParticipants.map((participant,participant_index)=>{
return <TouchableOpacity>
<FriendCardAvatar key={participant_index} friend={participant} />
</TouchableOpacity>
})}
</View>
)
Whenever the setShowParticipants is called it automatically re-renders the View of the App no need to do something else unlinke Javascript/Jquery
Upvotes: 0