Skip to content

how to implement search API in react native

I have Text Input like this

  <CustomInput
            value={searchInput}
            onChangeText={(e) => func(e)}
            mainStyle={{ width: "81%" }}
            placeholder="Search"
          />

Now I have func like this

const func = async (searchText) => {
    setSearchInput(searchText);
    searchAPI();
  };

this is my API calling code

const searchAPI = async () => {
    try {
      const data = new FormData();
      data.append("string_search", searchInput);
      setActivityIndicatorVal(true);
      let response = await fetch(
        "APILINK",
        {
          method: "POST",
          body: data,
          header: {
            "Content-Type": "multipart/form-data",
          },
        }
      );
      var json = await response.json();
      if (json.status == 1) {
        setActivityIndicatorVal(false);
        setList(json.data);
      } else {
        setActivityIndicatorVal(false);
        console.log("Error");
        getServiceList();
      }
    } catch (e) {
      setActivityIndicatorVal(false);

      Alert.alert("Error", "Error Massage : " + e, [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel",
        },
        { text: "OK", onPress: () => console.log("OK Pressed") },
      ]);
      return;
    }
  };

Now my question is Result is searing and showing correctly as I started typing in text box. But I remove all text from text input by back pressing keyboard button. then It should show all result. But it only showing That keyword which I remove recently by back press keyboard button. please help thanks.

Answer

While the user typing, searchAPI receives old input value due to how to React state update and component rendering works.

Try this refactor.

const func = async (searchText) => {
    setSearchInput(searchText);
  
  //This function execute before component rerender.
  // always pass input text value not rely on state value
    searchAPI(searchText);
  };

Then searchAPI

const searchAPI = async (searchQuery) => {
    try {
      const data = new FormData();
      data.append("string_search", searchQuery);
      setActivityIndicatorVal(true);
      let response = await fetch(
        "APILINK",
        {
          method: "POST",
          body: data,
          header: {
            "Content-Type": "multipart/form-data",
          },
        }
      );
      var json = await response.json();
      if (json.status == 1) {
        setActivityIndicatorVal(false);
        setList(json.data);
      } else {
        setActivityIndicatorVal(false);
        console.log("Error");
        getServiceList();
      }
    } catch (e) {
      setActivityIndicatorVal(false);

      Alert.alert("Error", "Error Massage : " + e, [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel",
        },
        { text: "OK", onPress: () => console.log("OK Pressed") },
      ]);
      return;
    }
  };

You can improve user experience and save server resources by debouncing search queries and only querying the database when the user finishes typing the search query.

// Utilitiy debounce function

function debounce(fn, wait) {
  var timeout;
  return function () {
    var ctx = this,
      args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      fn.apply(ctx, args);
    }, wait || 500);
  };
}

const debouncedSearch = debounce(func, 500);

<CustomInput
    onChangeText={debouncedSearch}
    mainStyle={{ width: "81%" }}
    placeholder="Search"
  />