Home > Back-end >  Re render flat list when data change cause infinite loop React Native
Re render flat list when data change cause infinite loop React Native

Time:08-19

I have two screens. Approve List and Approve Detail. When data approved in Approve Detail, page navigate to Approve List. Then approved data should disapear from FLatList. How to remove FlatList item when data approved? or how to re render FlatList when data change? Here is my code:

Approve List:

const Approve = ({ navigation }) => {
  const [rekomendasi, setRekomendasi] = useState({})
 // other code
 const getRekomendasi = async (token, bagian) => {
    try {
        const response = await sippApi.get(`/penjaminan?bagian=${bagian}`, {
            headers: {
                Auth: token
            }
        });
        setRekomendasi(response.data.data)
        console.log(rekomendasi)
    } catch (error) {
        console.log(error)
    }
 }
 useEffect(() => {
    getToken();
    getUserData()
    getRekomendasi(token, userData.bagian);
 }, [setToken, setUserData, rekomendasi]); // if I pass rekomendasi here, make infinite loop on api request

 return (
  <FlatList
    onRefresh={() => onRefresh()}
    refreshing={isFetching}
    removeClippedSubviews
    style={{ marginTop: 2 }}
    data={rekomendasi}
    keyExtractor={rekom => rekom.penjaminan.nomor_rekomendasi}
    renderItem={({ item }) => {
    return (
       <TouchableOpacity onPress={() => navigation.navigate("ApproveDetail", { id: item.penjaminan.nomor_rekomendasi, bagian: userData.bagian })}>
            <ApproveList
               plafond={item.value}
               kantor={item.nama_kantor}
               nomor_rekomendasi={item.nomor_rekomendasi}
               produk={item.skim}
              />
         </TouchableOpacity>
        )
      }}
    showsHorizontalScrollIndicator={false}
  />
)
}

If I pass value on second argument on UseEffect, it cause infinite loop on API request. If not, my FlatList cant re render when data change. What should I do?

Thanks for help

CodePudding user response:

You have to remove the rekomendasi dependency in the useEffect to avoid infinite loop, it's only for init data :)

What is the purpose of onRefresh function in the FlatList ? Instead you could put the getRekomendasi function to trigger a new call and your data will be updated

CodePudding user response:

try to separate the functions to two useEffects

 useEffect(() => {
    //<-- write your getToken() and getUserDate() here 
    getToken();
    getUserData()
 }, []);
 useEffect(() => {
    const getRekomendasi = async (token, bagian) => {
    try {
        const response = await sippApi.get(`/penjaminan?bagian=${bagian}`, {
            headers: {
                Auth: token
            }
        });
        setRekomendasi(response.data.data)
        console.log(rekomendasi)
    } catch (error) {
        console.log(error)
    }
 }
 getRekomendasi(token, userData.bagian);

 },[token,userData.bagian]);
  • Related