Hasut92
Hasut92

Reputation: 11

Updating FlatList data with useState infinitely recurs in React Native

I'm trying to set the data for a flatlist with useState, but updating the state causes the component to re-render, so it calls the getInventory function again and infinitely recurs, crashing the app. I'm using a function component, not class. If I put the getInventory bit in a useEffect, it doesn't crash, but the useEffect function in the InventoryItem components is constantly called. I can't see what I'm doing wrong

    const [data, setData] = useState([]);

    getInventory().then((list) => {
        setData(list)
    })    

    const renderItem = ({item}) => {
        return <InventoryItem item={item}/>
    };

    return (
        <SafeAreaView>
            <FlatList       
                data={data}
                renderItem={renderItem}
                keyExtractor={item => item.id}
            />  
        </SafeAreaView>
    );

Upvotes: 0

Views: 799

Answers (2)

Ori Drori
Ori Drori

Reputation: 192857

Use useEffect with an empty dependencies array, so it would run only once:

useEffect(() => {
  getInventory().then((list) => {
      setData(list)
  })
}, [])    

And you can also remove the redundant arrow function, since setData is a function that expects a single argument:

useEffect(() => {
  getInventory().then(setData)
}, [])

Upvotes: 1

Liki Crus
Liki Crus

Reputation: 2062

You should not call setState function in component's body.

Instead you can run it on useEffect.

useEffect(()=>{
    getInventory().then((list) => {
        setData(list)
    })    
}, [])

Upvotes: 0

Related Questions