Home > Software engineering >  How to implement pull to refresh with FlatList in functional React Native?
How to implement pull to refresh with FlatList in functional React Native?

Time:02-19

Here is my attempt:

import {View, Text, FlatList, Button} from 'react-native';
import React, {useState} from 'react';

const List = () => {
  const data = ['test1', 'test2', 'test3'];
  const [test, setTest] = useState(data);
  return (
    <View style={{alignItems: 'center'}}>
      <Text>List</Text>
      <FlatList
        data={data}
        numColumns={1}
        renderItem={({item, index}) => <Text>{item}</Text>}
        // onRefresh={}

        refreshing={false}
      />
      <Button title="addData" onPress={() => data.push('tset4')} />
      <Button title="show" onPress={() => console.log(data)} />
      <Button title="test" onPress={() => console.log(data)} />
    </View>
  );
};

export default List;

CodePudding user response:

Here how you would implement that (I added comments in the code):

import {View, Text, FlatList, Button} from 'react-native'; import React, {useState, useEffect} from 'react';

const List = () => {
  const data = ['test1', 'test2', 'test3'];
  const [test, setTest] = useState(data);
  const [refreshing, setRefreshing] = useState(false);

  useEffect(()=>{
    if(refreshing){
     // do your heavy or asynchronous data fetch
     setTest([...test, "test4"]); //

     // set the refreshing back to false
     setRefreshing(false);
    }
  },[refreshing])
  return (
    <View style={{alignItems: 'center'}}>
      <Text>List</Text>
      <FlatList
        data={data}
        numColumns={1}
        renderItem={({item, index}) => <Text>{item}</Text>}
        refreshing={refreshing}
        onRefresh={()=>setRefreshing(true)}
        refreshing={refreshing}
      />
      <Button title="addData" onPress={() => data.push('tset4')} />
      <Button title="show" onPress={() => console.log(data)} />
      <Button title="test" onPress={() => console.log(data)} />
    </View>
  );
};

export default List;

CodePudding user response:

You are missing the basics of React. Check this example.

https://snack.expo.dev/@nazrdogan/233ac3

  • Related