Yes, it is possible to load a local JSON file using fetch in a React application. However, you need to ensure that the path to the JSON file is correct and that the file is accessible within the context of your application when it's served by your web server or development server.
Here's how you can do it:
-
Make sure your
datas.jsonfile is located in the public directory or is accessible through the web server. If you're using Create React App, you can place it in thepublicfolder. -
Use
fetchwith the correct path to the JSON file. If the file is in the public folder, you can reference it with a path relative to the public directory.
Here's an example of how you might load the JSON file using fetch:
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
// If you're using Create React App and the file is in the public folder
fetch('/datas/data.json')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => setData(data))
.catch(error => console.error('There has been a problem with your fetch operation:', error));
}, []);
return (
<div>
{/* Render your data here */}
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
</div>
);
}
export default MyComponent;
In this example, the fetch call is made to /datas/data.json, which assumes that data.json is located at public/datas/data.json. The useEffect hook ensures that the fetch call is made when the component mounts.
If you're not using Create React App or your file is not in the public directory, you'll need to adjust the path accordingly. Remember that when using fetch, the path is relative to the root of the server, not the file system.
Regarding restrictions, when using Create React App, you cannot fetch local files from the src directory directly with fetch because they are not served by the web server. You would need to import them as modules instead, or move them to the public directory.