Reputation: 1
Here is the code I have written to filter some items:
const SearchScreen = () => {
const [term, setTerm] = useState('');
const [results, setResults] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const searchApi = async () => {
try {
const response = await yelp.get('/search', {
params: {
limit: 30,
term,
location: 'san jose'
}
});
setResults(response.data.businesses);
} catch (e) {
setErrorMessage('Ooops!!! Something went wrong.')
}
};
const filterResultsByPrice = price => {
// price === '$' || '$$' || '$$$'
return results.filter(result => {
return result.price === price;
});
};
return (
<View>
<SearchBar term={term} onTermChange={setTerm} onTermSubmit={searchApi} />
{errorMessage ? <Text style={styles.errorText}>{errorMessage}</Text> : null}
<Text>Total {results.length} results are found.</Text>
<ResultsList results={filterResultsByPrice('$')} title="Cost Effective" />
<ResultsList results={filterResultsByPrice('$$')} title="Bit Pricer" />
<ResultsList results={filterResultsByPrice('$$$')} title="Ambanis Only" />
</View>
);
};
I have been using this code and again and again I'm getting sometimes it works and sometime it throw this error on the terminal:
results.filter is not a function. (In 'results.filter(function (result) {
return result.price === price;
})', 'results.filter' is undefined)
Please help me resolving this. i am not able to find the root cause of this problem.
Upvotes: 0
Views: 26
Reputation: 2178
I think the problem is when you initialize the results variable as a an empty string, so when you call filter() on a string you get an error. Try to change the initialization to an empty array:
const [results, setResults] = useState([]);
Upvotes: 1