Ashok R
Ashok R

Reputation: 20766

Array.prototype.filter() is not giving expected output when i am using in my reducer

import {
  SEARCH_CHAT_FROM_RECENT_CHAT_CONTAT_LIST,
  GET_RECENT_CHAT_CONTAT_LIST_REQUEST,
  GET_RECENT_CHAT_CONTAT_LIST_SUCCESS,
  GET_RECENT_CHAT_CONTAT_LIST_FAILURE
} from "../actions/action-types";

const INTIAL_STATE = {
  response: null,
  error: null,
  loading: false,
  searchResults: null,
};

searchChatFromRecentChatContactList = (state, text) => {
    if(state.response && state.response.length > 0) {
        const response = [...state.response];
        const searchResults = response.filter(item => item.displayName.includes(text));
        return searchResults;
    }
    return [];
}

export default (state = INTIAL_STATE, action) => {
  switch (action.type) {
    case GET_RECENT_CHAT_CONTAT_LIST_REQUEST:
      return { ...state, loading: true, response: null, error: null, };
    case GET_RECENT_CHAT_CONTAT_LIST_SUCCESS:
      return { ...state, response: action.payload, loading: false};
    case GET_RECENT_CHAT_CONTAT_LIST_FAILURE:
      return { ...state, response: null,  error: action.payload, loading: false };
        case SEARCH_CHAT_FROM_RECENT_CHAT_CONTAT_LIST:
            return {...state, searchResults: searchChatFromRecentChatContactList(state, action.payload)};
    default:
      return state;
  }
};

I have array of strings in my state.response but for some reason my below method is always returning [];

state.response = [{displayName: 'someText'}, {displayName: 'someText otherText'];

input:

searchChatFromRecentChatContactList(state, 'SomeText')

output:

[];

Upvotes: 1

Views: 69

Answers (2)

Denis Rybalka
Denis Rybalka

Reputation: 1871

You can still improve it, destruction is not needed here because of nature of Array.prototype.filter, it returns newly created array

    searchChatFromRecentChatContactList = (state, text) => {
        const searchText = text.toLowerCase();
        return state.response && state.response.length ?
         state.response.filter(item => item.displayName.includes(searchText)) : [];
   }

Upvotes: 1

Ashok R
Ashok R

Reputation: 20766

I did silly mistake :(

searchChatFromRecentChatContactList = (state, text) => {
    if(state.response && state.response.length > 0) {
        const searchText = text.toLowerCase();
        const response = [...state.response];
        const searchResults = response.filter(item => {
            if(item.displayName.includes(searchText)) {
                return true;
            } else {
                return false;
            }
        });
        return searchResults;
    }
    return [];
}

text.toLowerCase(); //I should have done this. :-)

Upvotes: 0

Related Questions