Search code examples
javascriptjsonreact-nativereact-hooksreact-native-flatlist

How to read data from json file and use it to show in view component in react native?


I need to show "Top rated" in separate FlatList and the content which is courses inside it like how udemy shows its content. But I am new to react native never made such an app so I don't know how to fetch the data from the JSON file and then show it like this.

json file : https://drive.google.com/file/d/1l9J34syhsly7S43OzGar4RQN3d6g_yZn/view?usp=sharing

I have also attached the UI images to explain what I am trying to say and how I wanted to show my json data.

enter image description here

const Data = require("../Data/static_courses_data.json");
const CategoriesScreen = (props) => {
  const renderGridItem = (itemData) => {
    return (
      <CategoryGrid
        title={itemData.item["Title"]}
        imgUrl={itemData.item["image-url"]}
        onSelect={}
      ></CategoryGrid>
    );
  };
  return (
    <View>
      <FlatList data={Data} renderItem={renderGridItem} numColumns={2} />
    </View>
  );
};

I have also tried like this but it gives me an error saying Object is not a constructor(evaluating 'new_meal.default)


Solution

  • By directly importing your .json file you can do the following, however the items are not separated by categories for your specific case. I just took all the titles for an example.

    First you use Object.keys to get all the keys from your Top Rated and then use Object.values to get their values

    This link might be helpful: https://www.samanthaming.com/tidbits/76-converting-object-to-array/

    import React, {useEffect, useState} from 'react';
    import {View, Text, FlatList} from 'react-native';
    
    import data from './data.json';
    
    const App = () => {
      const [filteredItems, setFilteredItems] = useState([]);
      const [categories, setCategories] = useState();
    
      useEffect(() => {
        setFilteredItems([]);
        setCategories(Object.keys(data['Top Rated']));
      }, []);
    
      useEffect(() => {
        if (categories) {
          categories.map(category => {
            setFilteredItems(prevState => [
              ...prevState,
              Object.values(
                data['Top Rated'][`${category}`].map(item => `${item.Title}\n`),
              ),
            ]);
          });
        }
      }, [categories]);
    
      return (
        <View style={{flex: 1}}>
          <FlatList
            data={filteredItems}
            renderItem={({item}) => <Text>{`${item}\n`}</Text>}
          />
        </View>
      );
    };
    
    export default App;