Home > OS >  How can I get dynamically updating Flatlist in react-native?
How can I get dynamically updating Flatlist in react-native?

Time:11-11

I am working on a Ble device, I used react-native-ble-manager, useState, and useEffect to get notifications from event listeners and try to show them on App. I have posted a part of the code related to incoming data.

const [dataTest, setDataTest] = useState([]);
const handleUpdateValueForCharacteristic = (data) => {
  setDataTest(data.value); // data.value is a object incoming every one second from device.
};

useEffect(() => {
  bleManagerEmitter.addListener("BleManagerDidUpdateValueForCharacteristic", handleUpdateValueForCharacteristic);
}, []);

const renderData = (item) => {
  return (
    <View>
      <Text>{item}</Text>
    </View>
  );
};

return (
  <>
    <SafeAreaView>
      <FlatList 
       data={dataTest} 
       renderItem={({ item }) => renderData(item)} />
    </SafeAreaView>
  </>
);

This code, It showing only the latest events are coming from the device. But I need a list that contains older and new upcoming events so that I can scroll the events data.

CodePudding user response:

You almost got it. Your handleUpdateValueForCharacteristic function is the issue here.

Currently, you are overwriting the previous state (thus forgetting al previous values) by setting the state to new data.value. You want to append incoming data to the existing results, instead of overwriting them.

So you could do something like this:

const [dataTest, setDataTest] = useState([]);

const handleUpdateValueForCharacteristic = (data) => {
  const prevData = [...dataTest];
  prevData.unshift(data.value); // unshift adds elements to the beginning of an array
  
  // instead of using the incoming data.value, we use the prevData array since we just added the new value to it.
  setDataTest(prevData);
};

CodePudding user response:

I asked the same question on Reddit. The solution provided by __o_0 worked for me:

const handleUpdateValueForCharacteristic = useCallback(({value, peripheral, characteristic, service}) => {
const data = bytesToString(value);
setDataTest(prevData => {
return [...prevData, data]});},[])

const renderItem = ({item, index}) => {
return ( 
<View><Text>{index}</Text></View>);};
    
const keyExtractor=(item,index,) => \${index}`;`

return (
    <>
    <SafeAreaView>
    <FlatList
    data={dataTest}
    renderItem={renderItem}
    keyExtractor={keyExtractor}
    />
    
    </SafeAreaView>
    </>
    );
    };
  • Related