Gun
Gun

Reputation: 33

react native flatlist value doesn't get updated /re-rendered

I have a flatlist where it gets the itemCount from another page, I increment it with a button, its value changes but won't be seen on the screen without pressing ctrl-s or going to another page and return.

<FlatList 
extraData={store}
data={store}
renderItem={({ item }) => {
  return (
      <View style={styles.itemCountView}>
        <TouchableOpacity style={styles.up}
          onPress={() => item.itemCount++}>
          <MaterialIcons name="arrow-drop-up" size={36} color="#ddd"/>
        </TouchableOpacity>
        <Text style={styles.itemCountText}>{item.itemCount}</Text>
      </View>
  )
}}/>    

am I missing something? Maybe using the extraData the wrong way?

any type of help is appreciated

Upvotes: 2

Views: 2165

Answers (3)

hiren khatri
hiren khatri

Reputation: 244

Just add keyExtractor to your Flatlist

keyExtractor={(item, index) => index.toString()}

and it should look like this

   <FlatList 
    extraData={store}
    data={store}
    keyExtractor={(item, index) => index.toString()}
    renderItem={({ item }) => {
      return (
          <View style={styles.itemCountView}>
            <TouchableOpacity style={styles.up}
              onPress={() => item.itemCount++}>
              <MaterialIcons name="arrow-drop-up" size={36} color="#ddd"/>
            </TouchableOpacity>
            <Text style={styles.itemCountText}>{item.itemCount}</Text>
          </View>
      )
    }}/> 

Upvotes: 0

Vijeeth
Vijeeth

Reputation: 5

You can map it like below

{data.map({ item, i }) => {
  return (
      <View style={styles.itemCountView} key={i}>
        <TouchableOpacity style={styles.up}
          onPress={() => item.itemCount++}>
          <MaterialIcons name="arrow-drop-up" size={36} color="#ddd"/>
        </TouchableOpacity>
        <Text style={styles.itemCountText}>{item.itemCount}</Text>
      </View>
  )
}}

Upvotes: -1

user9106403
user9106403

Reputation:

to re-render the flat list you have to pass the variable in extraData which is changing its value.

extraData prop - It re renders the flat list when the given variable changes its value.

You can also manage with state variable like eg below : -

    const [refreshList, setRefreshList] = useState(false);

    setRefreshList(true);                // set this true where you need

    <FlatList
      data={item.punch_list_inspection}
      style={style.content}
      renderItem={renderItem}
      keyExtractor={item => item.id}
      extraData={refreshList}                  //pass variable here.
      ItemSeparatorComponent={FlatListItemSeparator}
    />

Upvotes: 1

Related Questions