I am using the <SearchBar>
from react-native-elements
and I'm trying to have it so that when the user pressed enter
or return
on the keyboard the project will execute a function.
here is my code
const CategoryScrn = (props) =>{
const [searchAPI, results, errorMessage] = searchResults();
const [term, setTerm] = useState('')
const city = props.navigation.state.params.city;
const category = props.navigation.state.params.category;
useEffect(() => {
searchAPI(city,category,'');
}, [])
return(
<SearchBar
placeholder="Search"
onChangeText={setTerm}
onSubmitEditing={searchAPI(city, category,`${term}`)}
value={term}
inputStyle={styles.input}
inputContainerStyle={styles.inputContainer}
containerStyle={styles.container}
placeholderTextColor='white'
/>
)}
the useEffect
function works completely fine so I know there isn't an issue in my API call. However when I enter a text in the SearchBar
(sometimes before I even enter anything) the app will crash and I will be an error of
Invariant Violation: expected 'onSubmitEditing' listener to be a function, instead got a value of 'object' type
You need to change this:
onSubmitEditing={searchAPI(city, category,`${term}`)}
to...
onSubmitEditing={() => searchAPI(city, category,`${term}`)}
Think of it this way. Every time the component is re-rendered, each line of code is being run again. In your original version, this means the function will be executed with every single render.
In the new version, it just means the function is declared, but not run. You're just making it available to the SearchBar component to execute when the user presses the search button.
Hope that makes sense. You'll see this exact scenario come up a lot! :)