-1

I created a custom component MyCustomList which is just a wrapper of FlatList. There are three props items, getMore, loading. This post focuses on the passed in loading prop only.

const MyCustomList = ({items, getMore, loading}) => {
      // console shows 'false'
      console.log(loading) 
      
      // use the 'loading' as the default value for the state variable
      const [isLoading, setIsLoading] = useState(loading);

      const myFooter = () => {
           // console shows undefined, why? Shouldn't it be the default value 'false'?
           console.log(isLoading});
            ...
      }
      return (
          <FlatList
            keyExtractor={keyExtractor}
            data={items}
            renderItem={renderItem}
            onEndReached={getMore}
            onEndReachedThreshold={0}
            ListFooterComponent={myFooter}
    />
  );
  ...
  export default MyCustomList;
}

In above custom component, parent component passed in the loading prop with value false, at runtime when swipe the list to bottom, the myFooter is called but the state variable isLoading is logged with value undefined. Why?

Leem.fin
  • 40,781
  • 83
  • 202
  • 354

2 Answers2

0

change to this only

const MyCustomList = ({items, getMore, loading = false}) => {

....

mainak
  • 1,886
  • 2
  • 9
  • 19
0

Change your code like below, we setting the isLoading state in useEffect

 import React, { useState, useEffect } from 'react';//add
 
 const MyCustomList = ({items, getMore, loading}) => {
           // console shows 'false'
           console.log(loading) 
           
           // use the 'loading' as the default value for the state variable
           const [isLoading, setIsLoading] = useState(loading);
     
           useEffect(() => {
             setIsLoading(loading)
            }, []);
 
           const myFooter = () => {
                // console shows undefined, why? Shouldn't it be the default value 'false'?
                console.log(isLoading});
                 ...
           }
           return (
               <FlatList
                 keyExtractor={keyExtractor}
                 data={items}
                 renderItem={renderItem}
                 onEndReached={getMore}
                 onEndReachedThreshold={0}
                 ListFooterComponent={myFooter}
         />
       );
       ...
       export default MyCustomList;
     }
jamal
  • 1,007
  • 1
  • 11
  • 26