I am trying to read a JSON-file
from my local drive. I wrote a code for this (method below):
readFile() {
let arr = {}; //make arr global
let input, file, fr;
if (typeof window.FileReader !== 'function') {
alert('File API is not supported');
return;
}
input = document.getElementById('fileinput');
if (!input.files[0]) {
alert('Please select a file before clicking import', {
timeout: 2000, className: 'alert-warning' });
return;
}
file = input.files[0];
fr = new FileReader();
fr.onload = Data;
fr.readAsText(file);
function Data(e) {
let lines = e.target.result;
//console.log(lines); //test:ok
arr = JSON.parse(lines);
//console.log(arr.name); //test:ok
}
}
It works, but I want to access arr
-variable from another function testMyArr
to use it like this:
testMyArr() {
const test = this.readFile.Data.arr; //error
//console.log(test);
}
I am getting this error: Cannot read property 'readFile' of null
.
testMyArr
is fired when I clik a button.
I am extremely new to JavaScript and Reactjs so any suggestions/help is very appreciated. How to access arr
?