Search code examples
reactjsreact-nativefetchreact-native-flatlist

React Native - display promised images in flatlist


I currently have multiple categories, and each of them have an array that contains the names of images. These arrays are fetched from a JSON file, I hope to use a flatList to display them. However when I do the following attempt, it says cannot read property '0' of undefined...

export default function display() {

const [all, setAll] = useState([])

const fetching = async() => {

     ... //code that fetches the JSON file

     setImages([{title: "A", arr: arrA},
                    {title: "B", arr: arrB},
                    {title: "C", arr: arrC}]
}

useEffect(() => {
    fetching();
}, [])

...

    const display = ({arr}) => ... //function that displays the pictures
 

    const Item = ({title, arr}) => {
        return(
        <View style={styles.categoryContainer}>
            
            {display(arr)}
            <Text style={styles.tags}>{title}</Text>

        </View>
        )
    }

    const renderItem = (item) => {
        return(
            <Item title={item.title}
                arr={item.arr}/>
        ) 
    }

    return (
        <View> 
            {console.log(all)}
            <FlatList
             data={all}
             renderItem={renderItem}
             keyExtractor={item => item.title}/>
        </View>
    )
}

The console.log in the return statement shows this: console.log(all)

Which part of my code is wrong? Any help will be appreciated!


Solution

  • Add a loader set it true when fetching the images and false after the call to fetch the images has done.

    const [all, setAll] = useState([]);
    const [isLoading, setLoader] = useState(true);
    
    const fetching = async() => {
    
     ... //code that fetches the JSON file
     setLoader(false);
     setImages([{title: "A", arr: arrA},
                    {title: "B", arr: arrB},
                    {title: "C", arr: arrC}]
     }
    

    Then in your render check if the loader is false or not

    return (
        <View> 
            { isLoading 
             ? <Text>Loading...</Text> 
    
             : <FlatList
                data={all}
                renderItem={renderItem}
                keyExtractor={item => item.title}/>
             }
        </View>
    )