skip to Main Content

How can I use ternary operator ( ? true : false ) or something else to remove the currrent logged in user from this list?

    const [users,setUsers] = useState("");

    useEffect(() => {
        axios.get("http://localhost:3000/api/v1/user/bulk?filter=" + filter)
            .then(response => {
                setUsers(response.data.user)
            })
    }, [filter])
    
    // Then using it like this, to get all the users data.

    {users.map(user => <User key={user._id} user={user} />)}

I have tried using this, but in terms of seperating users. I didn’t get it

2

Answers


  1.   const [users, setUsers] = useState([]);
      
      const loggedInUserId = "someUserId"; // Replace this with the actual logged-in user ID
      
    
      useEffect(() => {
        // Fetching users from API
        axios.get("http://localhost:3000/api/v1/user/bulk?filter=" + filter)
          .then(response => {
            // Filter out the logged-in user from the response data
            const filteredUsers = response.data.user.filter(user => user._id !== loggedInUserId);
            setUsers(filteredUsers); // Update the state with filtered users
          })
          .catch(error => {
            console.error("Error fetching users:", error);
          });
      }, [filter, loggedInUserId]); // Depend on 'filter' and 'loggedInUserId' for re-fetching
    
      return (
        <div>
          {/* Render users after filtering out the logged-in user */}
          {users.map(user => (
            <div key={user._id}>
              <h3>{user.name}</h3>
              {/* Add any other user data you'd like to display */}
            </div>
          ))}
        </div>
      );
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
    Login or Signup to reply.
  2. You could more efficiently, apply the useMemo hook to remove the logged in user, rather than removing it at time of render

    import { useState, useEffect, useMemo } from "react";
    import axios from "axios";
    
    const UsersList = ({ filter }) => {
      const [users, setUsers] = useState([]);
      const [loading, setLoading] = useState(false);
      const [error, setError] = useState(null);
    
      const loggedInUserId = "someUserId"; // Replace with actual logged-in user ID
    
      const fetchUsers = async () => {
        setLoading(true);
        try {
          const response = await axios.get(`http://localhost:3000/api/v1/user/bulk?filter=${filter}`);
          setUsers(response.data.user);
        } catch (error) {
          setError("Error fetching users");
          console.error(error);
        } finally {
          setLoading(false);
        }
      };
    
      useEffect(() => {
        fetchUsers();
      }, [filter]);
    
      const filteredUsers = useMemo(() => 
        users.filter(user => user._id !== loggedInUserId), [users, loggedInUserId]);
    
      if (loading) return <p>Loading...</p>;
      if (error) return <p>{error}</p>;
    
      return (
        <div>
          {filteredUsers.map(user => (
            <div key={user._id}>
              <h3>{user.name}</h3>
              {/* Add any other user data you'd like to display */}
            </div>
          ))}
        </div>
      );
    };
    
    export default UsersList;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

    Try it and comment if any doubts!!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search