Search code examples
jsontypescriptreact-nativefetch

Can't fetch local json using typescript "useEffect" in my RN Project


const jsonUrlExternal = require('https://reactnative.dev/movies.json'); //this works
const jsonUrlLocal  = require('../../json/MOCK_DATA.json'); //this doesn't work

When i use the first const jsonUrlExternal my app works well and fetch the data in the JSON. But when i simply change the URL to a local path it gives me an error: Type Error: Network request failed. Below, the code i'm using to fetch both local and external JSON file:

    const [data, setData] = useState([]);

    useEffect(() => {
        fetch(jsonUrlLocal) //the error appears exactly when i write this line
        .then((response) => response.json())
        .then((json) => setData(json.movies))
        .catch((error) => alert(error))
    })

And this is the FlatList i'm using to show the data from the JSON:

                <FlatList 
                    data={data}
                    keyExtractor={({id}, index) => id}
                    renderItem={({item}) => (
                        <Text>
                            {item.title}, {item.realeseYear}
                        </Text>
                    )}
                />

In short: when i use an external JSON from an URL my FlatList works, but when i simply change the URL for a local path/to/the/file/ the application returns me the error message: Type Error: Network request failed. OBS: the content inside local JSON is exactly the RAW Copy of the ExternalJson. I'm sure that the local JSON has no typing errors.


Solution

  • When you require() a local .json file, what I would expect to happen is to get an object instead of an URL. Fetch would then stingify that object and make a request to '[object%20Object]', which would naturally fail.

    Since you've already require()d it, there is no need to fetch it. It's already parsed and ready to use.

    const mockData = require('../../json/MOCK_DATA.json');
    
    
    
                    <FlatList 
                        data={mockData}
                        keyExtractor={({id}, index) => id}
                        renderItem={({item}) => (
                            <Text>
                                {item.title}, {item.realeseYear}
                            </Text>
                        )}
                    />