Home > Back-end >  Why isn't .filter method doing anything in my Expo app?
Why isn't .filter method doing anything in my Expo app?

Time:07-09

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.

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!

CodePudding user response:

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

  • Related