Search code examples
reactjsreact-nativeuse-statereact-state-management

State variable shows value 'undefined' though have set default value 'false'


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?


Solution

  • 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;
         }