So I'm listing some D&D creatures using a FlatList and I'm trying to implement a search bar where the user can get straight to what they're looking for.
function LandingPage() {
const [referencesList, setReferencesList] = useState([])
const [search, setSearch] = useState('')
const [page, setPage] = useState(1)
const renderItem = ({ item }) => (
<ReferenceItem name={`${item.name} CR: ${item.challenge_rating}`} key={item.slug} index={item.slug}/>
)
useEffect(() => {
api.get('/', {
params: {
fields: ['slug', 'name', 'challenge_rating'].join(),
limit: 100,
ordering: 'slug',
search,
page
}
}).then( response => {
setReferencesList([...referencesList, ...response.data.results])
}).catch( error =>
console.log(error)
)
}, [search, page])
return (
<View style={styles.container}>
<PageHeader title="Monsters List">
<SearchReferences search={setSearch}/>
</PageHeader>
<FlatList
data={referencesList}
renderItem={renderItem}
keyExtractor={item => item.slug}
onEndReachedThreshold={40}
onEndReached={() => setPage(page + 1)}
/>
</View>
)
}
export default LandingPage
The thing is, every time I try to search for something, it actually adds the result to the list I already have. I tried to solve this issue like this:
.then( response => {
let referencesResults = search === '' ? response.data.results : [...referencesList, ...response.data.results]
setReferencesList(referencesResults)
})
But now when I search for something and then wipe my search, it doesn't go back to the initial state of my list. Can someone help me with that? Or at least point me to some direction.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…