Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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"
  />

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda