Home > Blockchain >  Lodesh Filter is giving mid string data
Lodesh Filter is giving mid string data

Time:12-25

I am new with React Native and facing issue with Lodesh Filter. It is giving mid-string data. Ex if I want to search Mitsubishi and start typing "mi" it will not give me mitsubishi but if I start type "sub" then it is giving me mitsubishi.

Below is my code:

import React, { useEffect, useState }  from 'react';
import {View, Text, Button, TextInput, FlatList, ActivityIndicator, StyleSheet, Image} from 'react-native';
import filter from 'lodash.filter';


    const CarList = () => {
        const [isLoading, setIsLoading] = useState(false);
        const [data, setData] = useState([]);
        const [error, setError] = useState(null);
        const [query, setQuery] = useState('');
        const [fullData, setFullData] = useState([]);
       
        useEffect(() => {
            setIsLoading(true);
          
            fetch(`https://myfakeapi.com/api/cars/?seed=1&page=1&results=20`)
              .then(response => response.json())
              .then(response => {
                setData(response.cars);
                setFullData(response.cars);
          
                setIsLoading(false);
              })
              .catch(err => {
                setIsLoading(false);
                setError(err);
              });
          }, []);
    
          if (isLoading) {
            return (
              <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                <ActivityIndicator size="large" color="#5500dc" />
              </View>
            );
          }
        
          if (error) {
            return (
              <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                <Text style={{ fontSize: 18}}>
                  Error fetching data... Check your network connection!
                </Text>
              </View>
            );
          }
    
        const handleSearch = text => {
            const formattedQuery = text.toLowerCase();
            const filteredData = filter(fullData, user => {
                console.log(contains(user, formattedQuery));
              return contains(user, formattedQuery);
            });
            setData(filteredData);
            setQuery(text);
          };
          
          const contains = ({ car, car_model,car_color }, query) => {
          
            if (car.includes(query) || car_model.includes(query) || car_color.includes(query)) {
              return true;
            }
          
            return false;
          };
          function renderHeader() {
            return (
              <View
                style={{
                  backgroundColor: '#fff',
                  padding: 10,
                  marginVertical: 10,
                  borderRadius: 20
                }}
              >
                <TextInput
                  autoCapitalize="none"
                  autoCorrect={false}
                  clearButtonMode="always"
                  value={query}
                  onChangeText={queryText => handleSearch(queryText)}
                  placeholder="Search"
                  style={{ backgroundColor: '#fff', paddingHorizontal: 20 }}
                />
              </View>
            );
          }
      
        return (
         
          
            <View style={styles.container}>
          <Text style={styles.text}>Favorite Contacts</Text>
          <FlatList
           ListHeaderComponent={renderHeader}
            data={data}
            keyExtractor={({ id }) => id}
            renderItem={({ item }) => (
              <View style={styles.listItem}>
                <Image
                    source={{
                        uri: 'https://picsum.photos/200',
                      }}
                  style={styles.coverImage}
                />
                <View style={styles.metaInfo}>
                  <Text style={styles.title}>{`${item.car} ${
                    item.car_model
                  }`}</Text>
                </View>
              </View>
            )}
          />
        </View>
          
        );
    
     
    }

CodePudding user response:

Each car record have following fields:

{
    "id": 1,
    "car": "Mitsubishi",
    "car_model": "Montero",
    "car_color": "Yellow",
    "car_model_year": 2002,
    "car_vin": "SAJWJ0FF3F8321657",
    "price": "$2814.46",
    "availability": false
}

When you write mit, in contain function you are checking if(car.includes(text)...) but car name starts with an uppercase letter. You need to convert the car name in lowerCase before checking the text like this:

const contains = ({ car, car_model, car_color }, query) => {
    if (car.toLowerCase().includes(query) || car_model.toLowerCase().includes(query) || car_color.toLowerCase().includes(query)) {
        return true;
    }
    return false;
};
  • Related