0

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......
5
  • 1
    Have you tried using require()? Commented Jan 27, 2022 at 13:47
  • no, but I have used fetch, I only know how to load data from one file at a time. Commented Jan 27, 2022 at 13:50
  • 1
    These jsons files are into /src of your react app ? Commented Jan 27, 2022 at 14:01
  • no, they are on same level as /src Commented Jan 27, 2022 at 14:18
  • Can you upload the fetch logic, just need to update some logic to pull all files inside fetch Commented Jan 27, 2022 at 14:24

1 Answer 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.

Sign up to request clarification or add additional context in comments.

3 Comments

how to dynamicly create fileList, if i have more files It will be tough to add all files name in the fileList manually.
You can name your files dynamically i.e file1,file2, fiel3,.. You cannot get the directory information using client side js until you know the path.
You cannot get file details in a directory until you are from server (node.js,..). We can't do it in client-side scripting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.