Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  159] [ 1]  / answers: 1 / hits: 64023  / 7 Years ago, tue, october 17, 2017, 12:00:00

I have a problem since two days; I want read a local JSON from my public folder on my React application created with react-app.



This is my project structure:




  • public




    • data




      • mato.json (my .JSON file)



  • src




    • components




      • App.js





Why I put my file in public folder? If I build my project with file in src folder, my file will be include in the generated main.js by the command yarn build.



I want modify my json file without always rebuild my app.



So I can't use code like:



import Data from './mato.json'


…or:



export default { 'mydata' : 'content of mato.json'}
import data from 'mydata';


I tried to fetch my .json file but file scheme isn't friend with fetch() & chrome..



(Chrome error: “index.js:6 Fetch API cannot load file:///D:/projects/data/mato.json. URL scheme file is not supported.”)



This is my code for fetch:



fetch(`${process.env.PUBLIC_URL}/data/mato.json`)
.then((r) => r.json())
.then((data) =>{
ReactDOM.render(<App appData={JSON.stringify(data)}/>, document.getElementById('root'));
})


It's only works with Firefox. I also tried mode: 'cors' does not better.



And of course I don't have any server — it's a local project — so if someone knows how I can read my JSON file locally I will much appreciate.


More From » json

 Answers
42

I think your fetch argument is wrong. It should be



fetch('data/mato.json')

[#56204] Friday, October 13, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breanab

Total Points: 731
Total Questions: 95
Total Answers: 79

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
;