Updating FlatList data with useState infinitely recurs in React Native

715 views Asked by At

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>
    );
2

There are 2 answers

0
Ori Drori On BEST ANSWER

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)
}, [])
0
Liki Crus On

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

Instead you can run it on useEffect.

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