Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't .filter method doing anything in my Expo app?

I’m building an app with Expo and trying to apply a filter to fetchUsers function which pulls a list of Users from Database that are matched with the Authenticated User. I’m using AWS for backend. However, when I do fetchedUsers.filter it doesn’t return ANY User card.

So I have a function fetchMatches which pulls all the Users that have matched with the Authenticated user like so:

useEffect(() => {
  if (!me) {
      return;
  }
  fetchMatches();

 }, [me]);

 const fetchMatches = async () => {
    const result = await DataStore.query(Match, match => 
      match
      .isMatch('eq', true)
      .or(match => match.matchUser1Id('eq', me.id).matchUser2Id('eq', me.id))
      );
  setMatches(result);
  console.warn(result);

}

Then I have a function fetchUsers which takes the matches and filters them down to the matches user ids and compares them to the fetched User ids and excludes them if the userId equals the matched User id so you don’t have to swipe on somebody you’ve already matched with.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

useEffect(() => {
  
  if(!isUserLoading && user) {
    fetchUsers();
  }
}, [me, matches, user]);

const fetchUsers = async () => {
  let fetchedUsers = await DataStore.query(User);
  
    setUsers(fetchedUsers.filter(user => {
      matches.filter(match => 
        match.matchUser1Id !== user.id && match.matchUser2Id !== user.id
      )
    }));
}

So when I apply this filter to fetchedUsers then NO User cards are returned to Homescreen. However, when I remove the filter and just do setUsers(fetchedUsers) it returns the entire array of Users from the Database. As of now, there aren’t any unhandled promises showing up in console or any type of errors. It’s just simply not rendering. And I’m using Expo. Any help would be appreciated!

>Solution :

Don’t use the nested filter(), use some() to perform a test. And you need to return that result, so don’t put {} around it.

setUsers(fetchedUsers.filter(user =>
  matches.some(match =>
    match.matchUser1Id !== user.id && match.matchUser2Id !== user.id
  )
));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading