Home > Software design >  Updating FlatList data with useState infinitely recurs in React Native
Updating FlatList data with useState infinitely recurs in React Native

Time:04-14

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

CodePudding user response:

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 array function, since setData is a function that expects a single argument:

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

CodePudding user response:

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

Instead you can run it on useEffect.

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