Search code examples
reactjsreact-nativereact-hooksreact-native-flatlistreact-component

Cannot get datas on json with flatlist


I am using the Free Meal API with flatlist. I have Category component, Categories page, useFetch hook. I can't see Flatlist on screen. I can get console log of data but I can't reach datas with flatlist.

.env folder:

API_URL_CATEGORIES="https://www.themealdb.com/api/json/v1/1/categories.php"

API_URL_FILTER="https://www.themealdb.com/api/json/v1/1/filter.php?"

useFetch hook for getting the data in URL and returning Loading icon, Error if URL doesn't work and data for data in URL.

function useFetch(url) {

    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState();

    const fetchData = async () => {
        try {
        const {data: responseData} = await axios.get(url);
        setData(responseData);
        setLoading(false); }
        catch (error) {
            setError(error.message);
            setLoading(false);
        }
    };

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

    return {error, loading, data};
};

export default useFetch;

Category component:

const Category= ({category, onSelect}) => {
    return(
        <TouchableOpacity style={styles.container} onPress={onSelect}>
            <Image
             style={styles.image}
             source={{uri:category.strCategoryThumb}} />
            <Text style={styles.title}>{category.strCategory}</Text>
        </TouchableOpacity>
    )
}

export default Category;

Categories page:

const Categories = ({navigation}) => {

    const { error, loading, data } = useFetch(config.API_URL_CATEGORIES);

    console.log(data)

    const handleCategorySelect = strCategory => {
        navigation.navigate("Detail", {strCategory})
    }

    const renderCategory = ({item}) => <Category category={item} onSelect={() => handleCategorySelect(item.strCategory)}/>;

    if(loading) {
        return <Loading/>;
    }

    if(error) {
        return <Error/>;
    }

    return(
        <View style={styles.container}>
            <FlatList data={data} renderItem={renderCategory}/>
            <Text>Categorises</Text>
        </View>
    )
}   

export default Categories;

Solution

  • I think data is actually object that contains a property categories , which holds an array.

    try data.categories and I believe this should work fine.