Hello Guys Today i am going to show you how you can apply filter on map function.
So why i have to use filter method on map function well here is the problem i faced
<div>
{props.list.map((item) => {
return (
<div key={item._id}>
<div>
<h1>Username - {item.username}</h1>
<h1>Email - {item.email}</h1>
<h1>Password - {item.password}</h1>
</div>
<div>
<button
onClick={(e) => {
updateUser(item._id);
}} >
Update
</button>
</div>
);
})}
The problem i was facing is i have attached a button to update elements , i want to get the element id of that particular element which i want to update , here comes the filter method to rescue
...
const [updateId, setUpdateId] = useState("");
const [updateEmail, setUpdateEmail] = useState("");
const [updateUsername, setUpdateUsername] = useState("");
const [updatePassword, setUpdatePassword] = useState("");
const updateUser = (id) => {
const filtered = list.filter((user) => user._id === id);
setUpdateId(filtered[0]._id);
setUpdateEmail(filtered[0].email);
setUpdateUsername(filtered[0].username);
setUpdatePassword(filtered[0].password);
};
...
Explaination
- Here i have created a state called "updatedId" which will store the id of the element which i want to update.
- Then i created an arrow function "updatedUser" with parameter "id" this is the unique id which we will pass using our update button onClick method.
- Then we created a filter which returns the single user by comparing it to the id we have passed to the function if the id is present in the list.
Then we set the updatedId using "setUpdatedId(filtered[0]._id)", what it means the "filtered" is an array with only one element and "filtered[0]._id" means we are getting the id of that element and provide it to the "updatedId" state , now using this unique id ,we can update the user information by passing this id to the backend.
Also we have used "filtered[0].username","filtered[0].email" and "filtered[0].password",this will take the email, username and password assigned to that used id.
Thats it for this post.
THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION , PLEASE MENTION IT IN THE COMMENT SECTION.
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--
Also check these posts as well
https://dev.to/shubhamtiwari909/how-to-push-code-to-github-remote-respository-ifh
https://dev.to/shubhamtiwari909/styled-componenets-react-js-15kk
https://dev.to/shubhamtiwari909/introduction-to-tailwind-best-css-framework-1gdj