I am making an autocomplete for an input. I have an input which calls the queryText
function onChangeText
. The queryText
recieves a string and an array, it makes a new array with strings that match the passed string and updates state. The issue is my state is updated late.
In the code below if I type the letter "w" I get back the entire poi array instead of just walmart. But if I type "b" after I get only walmart (I should get nothing). If I erase "b" I get an empty array (I should get walmart). It seems like my autocomplete state is 1 keypress behind.
export default function IndoorForm() {
const poi = ["test1", "test2", "test3", "walmart"]
const [value, onChangeText] = React.useState('');
const [autocomplete, setAutocomplete] = React.useState([...poi]);
const [query, setQuery] = React.useState('');
const queryText = (text, poi) => {
let sanitizedText = text.toLowerCase();
const queryResult = poi.filter(location => location.includes(sanitizedText) !== false);
setAutocomplete([...queryResult]);
onChangeText(text);
console.log("-----New Text----")
console.log(queryResult); //this is displaying the correct array
console.log(text);
console.log(autocomplete); //this value is 1 behind what is expected
}
return (
<TextInput
key={autocomplete}
style={styles.input}
onChangeText={text => queryText(text, poi)}
value={value}
/>
);
}