jeudi 6 septembre 2018

Asking for guidance to combine filter() conditions

Below I have two filter methods that render a flatlist of items depending on the text input - thanks to you guys at StackOverflow. Shoutout to @T.J.Crowder

./Screen

    // Filter by Name

    let lcName = this.state.searchItemName.toLowerCase();

    let modItemListName = this.props.items.filter(
        (item) => item.name.toLowerCase().indexOf(lcName) !== -1    
    );


    // Filter by Location

    let lcLocation = this.state.searchItemLocation.toLowerCase();

    let modItemListLocation = this.props.items.filter(
        (item) => item.fullLocation.some(e => e.toLowerCase().indexOf(lcLocation) !== -1)
    );

./Component

class FilterItemName extends Component {

render() {
    return (
        <View>
            <TextInput 
                style = {styles.searchInput}
                placeholder="Name" 
                returnKeyType="search"
                onChangeText={this.props.onChangeText}
                onSubmitEditing={this.props.searchItemName}
            />
        </View>
    );
  }
}



class FilterItemLocation extends Component {

render() {
    return (
        <View>
            <TextInput 
                style = {styles.searchInput}
                placeholder="Name" 
                returnKeyType="search"
                onChangeText={this.props.onChangeText}
                onSubmitEditing={this.props.searchItemLocation}
            />
        </View>
    );
  }
}

Now I want to combine them so that they work individually (ie if I just input part of a name, it will filter by name, or by location etc) or together (ie input name and (part of) location, and filter accordingly).

I want to be clear. I'm not looking for you guys to write the code for me. I want to give it a go first. But I wanna know if my approach (logic-wise) makes sense.

Should I be looking to create some sort of handler property that consists of conditional statements and then() method?

Something like

searchHandler = () => {
if....input text into <FilterItemName /> and <FilterItemLocation />
  return modItemListName 
         .then(modItemListLocation) // filtering by name first then by location

else.....input text into <FilterItemName />
  return modItemListName ... or 
         input text into <FilterItemLocation />
  return modItemListLocation
}

Roughly speaking, is this the right approach? Hopefully this makes sense aha. Sorry for the crude code. I'm just spitballing at the moment.

Aucun commentaire:

Enregistrer un commentaire