1

I'm developing the feature in which when the user type in the TextInputand it filters the items in the array data and shows in the FlatList the result of the search, at the moment it works when I start typing the first time I render the screen, but when I start cancelling the text in the TextInput and try again it just returns empty arrays, and nothing shows in the FlatList, and also in useEffect I get the same array twice.

Array

Array [
  Object {
    "additional": Array [
      Object {
        "data": Array [
          Object {
            "id": 0,
            "price": 1,
            "selected": false,
            "title": "Ranch",
            "type": "Sides",
          },
          Object {
            "id": 1,
            "price": 1,
            "selected": false,
            "title": "Blue Cheese",
            "type": "Sides",
          },
          Object {
            "id": 2,
            "price": 1,
            "selected": false,
            "title": "Tomato Sauce",
            "type": "Sides",
          },
        ],
        "id": 0,
        "required": false,
        "title": "Sides",
      },
    ],
    "description": "vsjvnmvimrivmeirv",
    "id": 0.101,
    "image": "https://images.unsplash.com/photo-1623653387945-2fd25214f8fc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",   
    "price": 6.95,
    "title": "Garlic Knots",
  },
  Object {
    "additional": Array [
      Object {
        "data": Array [
          Object {
            "id": 0,
            "price": 1,
            "selected": false,
            "title": "Ranch",
            "type": "Sides",
          },
          Object {
            "id": 1,
            "price": 1,
            "selected": false,
            "title": "Blue Cheese",
            "type": "Sides",
          },
          Object {
            "id": 2,
            "price": 1,
            "selected": false,
            "title": "Tomato Sauce",
            "type": "Sides",
          },
        ],
        "id": 0,
        "required": false,
        "title": "Sides",
      },
    ],
    "description": "vsjvnmvimrivmeirv",
    "id": 0.102,
    "image": "https://images.unsplash.com/photo-1623653387945-2fd25214f8fc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",   
    "price": 6.95,
    "title": "Mozzerella Sticks",
  },
  Object {
    "additional": Array [
      Object {
        "data": Array [
          Object {
            "id": 0,
            "price": 0,
            "selected": false,
            "title": "Hot Sauce",
            "type": "Sauces",
          },
          Object {
            "id": 1,
            "price": 0,
            "selected": false,
            "title": "Medium Sauce",
            "type": "Sauces",
          },
        ],
        "id": 1,
        "required": true,
        "title": "Sauces",
      },
      Object {
        "data": Array [
          Object {
            "id": 0,
            "price": 1,
            "selected": false,
            "title": "Ranch",
            "type": "Sides",
          },
          Object {
            "id": 1,
            "price": 1,
            "selected": false,
            "title": "Blue Cheese",
            "type": "Sides",
          },
        ],
        "id": 0,
        "required": false,
        "title": "Sides",
      },
    ],
    "description": "vsjvnmvimrivmeirv",
    "id": 0.103,
    "image": "https://images.unsplash.com/photo-1623653387945-2fd25214f8fc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",   
    "price": 6.95,
    "title": "Buffalo Wings",
  },
  Object {
    "additional": Array [
      Object {
        "data": Array [
          Object {
            "id": 0,
            "price": 1,
            "selected": false,
            "title": "Ranch",
            "type": "Sides",
          },
          Object {
            "id": 1,
            "price": 1,
            "selected": false,
            "title": "Blue Cheese",
            "type": "Sides",
          },
          Object {
            "id": 2,
            "price": 1,
            "selected": false,
            "title": "Caesar",
            "type": "Sides",
          },
          Object {
            "id": 3,
            "price": 1,
            "selected": false,
            "title": "Honey Mustard",
            "type": "Sides",
          },
        ],
        "id": 0,
        "required": false,
        "title": "Sides",
      },
    ],
    "description": "vsjvnmvimrivmeirv",
    "id": 0.201,
    "image": "https://images.unsplash.com/photo-1512621776951-a57141f2eefd?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",   
    "price": 6.95,
    "title": "Garden Salad",
  },
  Object {
    "additional": Array [
      Object {
        "data": Array [
          Object {
            "id": 0,
            "price": 1,
            "selected": false,
            "title": "Ranch",
            "type": "Sides",
          },
          Object {
            "id": 1,
            "price": 1,
            "selected": false,
            "title": "Blue Cheese",
            "type": "Sides",
          },
          Object {
            "id": 2,
            "price": 1,
            "selected": false,
            "title": "Caesar",
            "type": "Sides",
          },
          Object {
            "id": 3,
            "price": 1,
            "selected": false,
            "title": "Honey Mustard",
            "type": "Sides",
          },
        ],
        "id": 0,
        "required": false,
        "title": "Sides",
      },
    ],
    "description": "vsjvnmvimrivmeirv",
    "id": 0.202,
    "image": "https://images.unsplash.com/photo-1512621776951-a57141f2eefd?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",   
    "price": 6.95,
    "title": "Greek Salad",
  },
  Object {
    "additional": Array [
      Object {
        "data": Array [
          Object {
            "id": 0,
            "price": 1,
            "selected": false,
            "title": "Ranch",
            "type": "Sides",
          },
          Object {
            "id": 1,
            "price": 1,
            "selected": false,
            "title": "Blue Cheese",
            "type": "Sides",
          },
          Object {
            "id": 2,
            "price": 1,
            "selected": false,
            "title": "Caesar",
            "type": "Sides",
          },
          Object {
            "id": 3,
            "price": 1,
            "selected": false,
            "title": "Honey Mustard",
            "type": "Sides",
          },
        ],
        "id": 0,
        "required": false,
        "title": "Sides",
      },
    ],
    "description": "vsjvnmvimrivmeirv",
    "id": 0.203,
    "image": "https://images.unsplash.com/photo-1512621776951-a57141f2eefd?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",   
    "price": 6.95,
    "title": "Caesar Salad",
  },
]

Screen

function Orders({ navigation, newOrder }) {
   
  const [search, setSearch] = useState("");
  const [filteredDataSource, setFilteredDataSource] = useState([]);

  useEffect(() => {
    const starCountRef = ref(dbMenu, 'menu');
    onValue(starCountRef, (snapshot) => {
      const data = snapshot.val();  <-------------------------------Array
      if (filteredDataSource.length == 0) {
      data.map((item) => {
        item.data.map((item) => {
          let array = filteredDataSource;
          array.push(item)
          setFilteredDataSource([...array])
        })
      })
     }
    });
    
  }, []);


  const searchFilterFunction = (text) => {
     if (text) {
       const newData = filteredDataSource.filter(function (item) {
         const itemData = item.title
           ? item.title.toUpperCase()
           : "".toUpperCase();
         const textData = text.toUpperCase();
         return itemData.indexOf(textData) > -1;
       });
       setFilteredDataSource(newData);
       setSearch(text);
       setShowSearch(true)
     } else {
       setFilteredDataSource(filteredDataSource);
       setSearch(text);  
     }
  };


    return (
      <View>
           <TextInput
            onChangeText={(text) => searchFilterFunction(text)}
            clearButtonMode='while-editing'
            style={styles.searchAddress}
            placeholder={'Search menu'}
            autoFocus={true}
            value={search}
            returnKeyType='search'
          />
              <FlatList
                data={filteredDataSource}
                keyExtractor={(item) => item.id}
                renderItem={({ item }) => {
                  return (
                    <TouchableOpacity key={item.id} onPress={() =>navigateToItemFromModal(item)}>
                        <Text>{item.title}</Text>
                        <Text>${item.price}</Text>
                    </TouchableOpacity>
                  )
                }} />
     </View>
     )
}

1 Answer 1

3

when you type in textInput you are searching from previous filtered data once the filtered data gets empty then all the next search will happen in empty array and you are just stuck with empty to avoid that take a dummy state which stores original data.

i have modified your code hope this helps

function Orders({ navigation, newOrder }) {
   
  const [search, setSearch] = useState("");
  const [filteredDataSource, setFilteredDataSource] = useState([]);
const [filteredDataOriginal, setfilteredDataOriginal] = useState([]);

  useEffect(() => {
    const starCountRef = ref(dbMenu, 'menu');
    onValue(starCountRef, (snapshot) => {
      const data = snapshot.val(); 
      if (filteredDataSource.length == 0) {
    let array = [];
      data.map((item) => {
        item.data.map((dataItem) => {
          array.push(dataItem)
        })
      })
          setFilteredDataSource([...array])
          setfilteredDataOriginal([...array])
     }
    });
    
  }, []);


  const searchFilterFunction = (text) => {
     if (text) {
       const newData = filteredDataOriginal.filter(function (item) {
         const itemData = item.title
           ? item.title.toUpperCase()
           : "".toUpperCase();
         const textData = text.toUpperCase();
         return itemData.indexOf(textData) > -1;
       });
       setFilteredDataSource(newData);
       setSearch(text);
       setShowSearch(true)
     } else {
       setFilteredDataSource(filteredDataOriginal);
       setSearch(text);  
     }
  };


    return (
      <View>
           <TextInput
            onChangeText={(text) => searchFilterFunction(text)}
            clearButtonMode='while-editing'
            style={styles.searchAddress}
            placeholder={'Search menu'}
            autoFocus={true}
            value={search}
            returnKeyType='search'
          />
              <FlatList
                data={filteredDataSource}
                keyExtractor={(item) => item.id}
                renderItem={({ item }) => {
                  return (
                    <TouchableOpacity key={item.id} onPress={() =>navigateToItemFromModal(item)}>
                        <Text>{item.title}</Text>
                        <Text>${item.price}</Text>
                    </TouchableOpacity>
                  )
                }} />
     </View>
     )
}
Sign up to request clarification or add additional context in comments.

1 Comment

Dheeraj beat me to it but it's a good answer. For what it's worth and if it helps I did a minimal demo of the same thing codesandbox.io/s/trusting-bohr-liueo9?file=/src/App.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.