Home > Enterprise >  Fetching External Nested Object Data and using Filtering on Response with a specific key
Fetching External Nested Object Data and using Filtering on Response with a specific key

Time:11-02

I'm having trouble getting my data into state so that my filtered function can do its filtering.

Here is my code:

  const [users, setUsers] = useState();
  const [query, setQuery] = useState();

  useEffect(() => {
    const getUsers = async () => {
      const { data, error } = await supabase.from("users").select();
      if (error) {
        console.log(error.message);
      }
      if (data) {
        setUsers(JSON.stringify(data));
      }
    };
    getUsers();
  }, []);

The "data" object that returns from the data is as follow

(2) [{…}, {…}]
0: {displayname: 'Tester'}
1: {displayname: 'The Other Tester'}
length: 2
[[Prototype]]: Array(0)

I JSON.stringify it so that I can use the toLowerCase function

The Filtered items function:

  const filteredItems = users.filter((user) => {
    user.toLowerCase().includes(query.toLowerCase());
  });

Below I do the normal mapping of filtered items to show them on the page etc.

I assume its because the JSON are 2 objects. How would I extract just the displayname only to use for filtering?

CodePudding user response:

You don't need JSON.stringify for all this.

Just store the users in an array and handle every displayname accordingly when you filter them

  const [users, setUsers] = useState([]);
  const [query, setQuery] = useState('');

  useEffect(() => {
    const getUsers = async () => {
      const { data, error } = await supabase.from("users").select();
      if (error) {
        console.log(error.message);
      }
      if (data) {
        setUsers(data);
      }
    };
    getUsers();
  }, []);
  
  
    const filteredItems = users.filter((user) => {
      user.displayname.toLowerCase().includes(query.toLowerCase());
    });
  • Related