0

I've got a react component and I'm tying to do a RegExp search on the value onchange. The function below runs each time the input changes, however the results make no sense. Tests (regex.test(usr.email)) that log out as true don't go through the if statement in the filter function...

search(data) {
    const { dispatch, users, filteredUsers } = this.props;
    const query = data.q || data.target.value;
    let sanitisedQuery;
    if (query === '' && filteredUsers.length < users.length) {
      console.log('empty string reset');
      return dispatch(setFilteredUsers([...users]));
    }

    if (query) {
      sanitisedQuery = query.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
      const regex = new RegExp(sanitisedQuery, 'gi');
      const fUsers = users.filter((usr) => {
        if (regex.test(usr.email)) {
          return usr;
        }
      });
      dispatch(setFilteredUsers(fUsers));
    }
  }

I've taken the logs out to make it clearer, but what I get back is:

?d41d:60 query r string
?d41d:63 regex /r/gi
?d41d:65 email <redacted> true //<-- the true is regex.test(usr.email)
?d41d:65 email <redacted> true
?d41d:67 returning user 
Object {email: <second email>, ...}
?d41d:65 email <redacted> false
?d41d:65 email <redacted> true
?d41d:65 email <redacted> false
?d41d:71 fUsers 
[Object]
?d41d:158 about to dispatch SET_FILTERED_USERS 
[Object]
?d41d:38 action 
Object {type: "SET_FILTERED_USERS", filteredUsers: Array[1]}
?d41d:114 user 
Object {email: <second email>, …}

Each email is tested and the first, second and fourth pass the test, yet only the second one is passed into the new array.

user1775718
  • 1,499
  • 2
  • 19
  • 32
  • One thing is certain: use `new RegExp(sanitisedQuery, 'i')` instead of `new RegExp(sanitisedQuery, 'gi')` – Wiktor Stribiżew Oct 06 '16 at 18:33
  • @WiktorStribiżew Actually yes, that makes sense I guess (sorry, tired). I would just have thought, given that it returns true that it would not have made a difference... still. If you put it as the answer then I'll mark it correct. – user1775718 Oct 06 '16 at 18:46
  • This is a second question with identical answer this evening. I prefer not to answer questions that are so frequent, with an evident single issue. The answer in the original question is quite enough. – Wiktor Stribiżew Oct 06 '16 at 19:14

0 Answers0