DEV Community

Cover image for Filter on map function in React JS
Mysterio
Mysterio

Posted on • Updated on

Filter on map function in React JS

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>
       );
     })}
Enter fullscreen mode Exit fullscreen mode

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);
  };


...
Enter fullscreen mode Exit fullscreen mode

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

Discussion (10)

Collapse
tylerjnewman profile image
Tyler Newman • Edited on

I would do it this way:

const [userId, setUserId] = useState("");
const updatedUser = list.find((user) => user._id === userId);
const { email, username, password } = updateUser;
Enter fullscreen mode Exit fullscreen mode

const updateUserId = (id) => setUpdateId(id) is redundant as well as you can just use setUserId directly

Collapse
lukeshiru profile image
Luke Shiru

Instead of running that find on every re-render, ideally you should use useMemo for that:

const { email, username, password } = useMemo(
    () => list.find(({ _id }) => _id === userId),
    [userId],
);
Enter fullscreen mode Exit fullscreen mode

This way you only run find when the userId changes.

Collapse
shubhamtiwari909 profile image
Mysterio Author

Will I be able to send this data to my backend to update each field of email , username and password seperately ?

Thread Thread
lukeshiru profile image
Luke Shiru

You should be able to do that, yep.

Thread Thread
shubhamtiwari909 profile image
Mysterio Author

Okayzz

Collapse
shubhamtiwari909 profile image
Mysterio Author

Yes but I needed 3 different states of email , username and password because i have three inputs which change these states and update the value using those input fields

Collapse
jamesthomson profile image
James Thomson

Personally I would group these as an object. They're all related, so why have seperate individual states, updaters, etc. for each?

Thread Thread
shubhamtiwari909 profile image
Mysterio Author

If i have to send this data (I'd,email,username and password) to the backend for MongoDb query then please write the short logic for it

Collapse
larsonnn profile image
Lars Feldeisen

It was a nice "reminder" to use proper functions.

Thread Thread
shubhamtiwari909 profile image
Mysterio Author

Okay i would try to re-code this thing
As i don't want to mess up the backend part which is already set and i am new to this πŸ˜‚πŸ˜‚