1

I am trying to load data from two separate .txt files into two different arrays, I have also tried loading in the data from .csv files.

I am getting empty arrays as the result.

Here is my code:

loadData = async () => {    
    var reader = new FileReader();
    var data1 = reader.readAsText("./file1.txt");
    var data2 = reader.readAsText("./file2.txt");
  
    this.setState({
      arr1: data1,
      arr2: data2
      
    });
    
    await console.log(this.state.arr1)
    

  };

After the console log, I am just getting

Array []

1 Answers1

0

You can also use fetch to read the file

fetch('/sample.txt')
    .then((r) => r.text())
    .then(text  => {
      this.setState({
      arr1: text
    },()=>console.log(this.state.arr1))
    }).catch(error => {
      // Maybe present some error/failure UI to the user here
    });
pandacode
  • 51
  • 1
  • 6
  • Hi, I have same problem as OP and when trying this get `[Unhandled promise rejection: TypeError: Network request failed]` – Samuelf80 Mar 04 '21 at 09:13
  • Hi, Can you share your code so I can find why this error occurs. – pandacode Mar 04 '21 at 10:06
  • Yeah, I just got this error, legit is the same code as you shared, just of course replaced my file path – Trey Collier Mar 04 '21 at 15:19
  • Add error handler(catch method) and check. I have updated it in my answer. – pandacode Mar 04 '21 at 16:27
  • It would be wonderful to use fetch(), but this isn't working for me, either. I tried using relative path (e.g. `./assets/file.txt`), but I am also getting the Network request failed message. – Todd May 02 '23 at 02:02