'FlatList: "Tried to get frame for out of range index NaN" with useEffect + fetch

I'm trying to render a FlatList with data coming from fetch. It worked before, but now it gives me the error ""Tried to get frame for out of range index NaN". I have an async function which await the fetch but my return (render) with FlatList is being called first. I've changed the fetch code to use useCallback(async() => ....) but it doesn't work. I can't put the fetch inside the useEffect because I need it elsewhere inside the component (refresh stuff). Here is my Component code:

function Home() {
    const [data, setData] = useState({});

    const getDataFromApi = useCallback(async() => {
        const u = await SecureStore.getItemAsync('user');
        const p = await SecureStore.getItemAsync('password');

        await fetch('https://arko.digital/wp-json/wp/v2/arko_alerta', {
        method: 'GET',
        headers: {
            'Authorization': 'Basic ' + Buffer.from(u + ':' + p).toString('base64'),
        }})
        .then((response) => response.json())
        .then((json) => {
            setData(json)
        })
        .catch((error) => {
            console.error(error);  
        });
    }, []);

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

    return (
        <View style={{flex: 1}}>
             <FlatList
                data={data}
                refreshing={refreshing}
                onRefresh={onRefresh}
                keyExtractor={({ id }, index) => id}
                ListHeaderComponent={<Text style={commonStyles.bigHeader}>Alertas</Text>}
                renderItem={({ item }) => (
                    <Alerta 
                        title={item.content.rendered.split('</b>')} 
                        content={item.content.rendered} 
                        time={item.date}
                        excerpt={item.excerpt.rendered}
                        hidden={true}
                    />
                )}
            /> 
        </View>
    );
}

export default Home;

Using console.log i've noticed that the fetch INDEED return an array of objects in a couple of seconds. The problem is that my FlatList is not awaiting the fetch call. What am I doing wrong? I'm a newbie

As I said, this worked before with a simple async function getDataFromApi(){ ... } outside useEffect and getDataFromApi() call inside useEffect.

Thanks in advance



Solution 1:[1]

make sure you are passing array to FlatList because FlatList are expecting an array of items.

change this useState declaration to const [data, setData] = useState([]);

And also make sure json is an array of items setData(json)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rahman Haroon