'How to load data from multiple json files in react
I have 10 json files in a directory inside react app. I need to search data and matching data could be any of the file. For this do i need toI load all data of each json file in the react state. If yes how to load all data of each json files in the react state.
If there any better way to do this please suggest me.
Directory structure like this:
students/
/level1.json
/level2.json
/level3.json
/more files......
Solution 1:[1]
Here is the sample snippet
//Have your static jsons inside public folder, So that after compilation react able to get the static files
const [fileData,setFileData] = useState([])
useEffect(()=>{
const fileList = ['level1' ,'level2' ,'level3']; //files list in public folder
fileList.forEach(filename => {
fetch(`./${filename}.json`).then(response => {
return response.json() //parse json
}).then(data => {
setFileData(files => [...files, {[filename]:data}]); // pushing json data by key of filename
}
)
})
},[])
fetch API will look for files like -> "http://localhost:3000/level1.json" which is actually the public directory, So if you use fetch. You need to move it under public folder.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Srimurugan Subramanian |
