Skip to content

Instantly share code, notes, and snippets.

@faustoct1
Created September 14, 2022 20:36
Show Gist options
  • Save faustoct1/d2c7d66cdd85fc2d26602d8d963f3ab6 to your computer and use it in GitHub Desktop.
Save faustoct1/d2c7d66cdd85fc2d26602d8d963f3ab6 to your computer and use it in GitHub Desktop.
Como fazer requests com InputText apenas quando parar de digitar
/*
Esse InputSearch faz o search / request / qq coisa depois de 500ms que parou de digitar a última letra.
Isso evita gerar requests desnecessários e entupir o backend com requests. Essa técnica de delay evita
fazer múltiplos requests e faz o request apenas quando parar de digitar.
Use:
<InputSearch open={true} close={()=>setSearching(false)} />
*/
import React, { useState, useEffect } from 'react';
import { TextInput, View, Text, TouchableOpacity, SafeAreaView, FlatList } from 'react-native'
import AntDesign from 'react-native-vector-icons/AntDesign'
export default InputSearch = (props) => {
const [loading,setLoading] = useState(false)
const [results,setResults] = useState(null)
const [text,setText] = useState(null)
const [_timeout,_setTimeout] = useState(null)
useEffect(()=>{
},[])
const onChangeText = async (text) => {
setText(text)
if(_timeout) clearTimeout(_timeout)
if(text && text.trim()){
_setTimeout(
setTimeout(async () => {
//Adicione aqui seu request e adicione ao results
setResults([...(results ? results : []), ...[text] ])
setLoading(false)
}, 500)
)
}
setLoading(false)
}
const getResults = () => (
loading ?
<Text>Typing</Text>
:
(
results ?
<FlatList
style={{backgroundColor:'#000',flex:1}}
data={results}
keyExtractor={(item,index) => index}
onEndReachedThreshold={0.1}
renderItem={({item,index}) => <Text style={{color:'#fff'}}>{item}</Text>} />
:
null
)
)
return (
<SafeAreaView style={{flex:1,backgroundColor:'#000',height:'100%'}}>
<TouchableOpacity style={{marginTop:10,marginLeft:10,alignItems:'flex-start'}} onPress={()=>{ setOpenModal(false);if(props.close)props.close() }}>
<AntDesign name={'close'} size={32} color={'#fff'} style={{textAlign:'left'}} />
</TouchableOpacity>
<View style={{flexDirection:'row',backgroundColor:'#000'}}>
{
!text &&
<View style={{position:'absolute',zIndex:1,left:15,top:20}}>
<AntDesign name={'search1'} size={20} color={'#999'}/>
</View>
}
<TextInput
style={{height: 40, borderColor: '#111', borderWidth: 1, borderRadius:5,color:'#fff',padding:5,marginTop:10,backgroundColor:'#111', justifyContent:'center',flex:1}}
underlineColorAndroid='transparent'
placeholderTextColor={'#999'}
placeholder={` Procurar `}
onChangeText={(text) => {setLoading(true);onChangeText(text)}}
value={text} />
</View>
{ getResults() }
</SafeAreaView>
)//
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment