Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

android - Having trouble using infinite FlatList together with a search

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's because here

setReferencesList([...referencesList, ...response.data.results])

you're appending your new results to the entire existing list, without deduplicating it.

It kind of looks like what you want is just

setReferencesList(response.data.results)

unless you'd like to cache previously returned results, which would require some additional logic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...